Is There Any Way To Modify The Objects Dynamically By Comparing On Key Value Pair
I am having a dynamic JSON array in below format, let main_object = [ { 'apple':[ { 'name':'aaaa', 'count':'1', 'filter':{
Solution 1:
Map method is only for array and hence you need to make the map over level1[rtype]
like,
level1[rtype].map()
Then to compare the name use,
if(item.name === updated_data[rtype][0].name) {
item = updated_data[rtype];
}
And working snippet as follows,
let main_object = [
{
"apple":[
{
"name":"aaaa",
"count":"1",
"filter":{
"type":{
"name":"test3"
}
}
},
{
"name":"bbbb",
"count":"9",
"filter":{
"type":{
"name":"test2"
}
}
}
]
},
{
"orange":[
{
"name":"cccc",
"count":"6",
"filter":{
"type":{
"name":"test"
}
}
}
]
}
]
let updated_data = {
"orange":[
{
"name":"cccc",
"count":"1234",
"type":{
"name":"updated_name"
}
}
]
}
let rtype = 'orange';
const altered =
main_object.map((level1,i) => {
if(level1[rtype] !== undefined){
const data = level1[rtype].map((item,index) => {
if(item.name === updated_data[rtype][0].name) {
item = updated_data[rtype];
}
return item;
})
if(level1[rtype] !== undefined){
level1[rtype] = data;
}
}
return level1;
})
console.log(altered);
Solution 2:
Try this below :
let rtype = 'orange';
main_object = main_object.map(function (item) {
if(Object.keys(item).indexOf(rtype) > -1){
item[rtype][0]['filter']['type']['name'] = updated_data[rtype][0]['type']['name'];
return item
}else {
return item
}
});
console.log(main_object)
Post a Comment for "Is There Any Way To Modify The Objects Dynamically By Comparing On Key Value Pair"