I'm trying to loop through an array of objects and if a nested object has a certain value change this value to something else.
In this example of dummy data if fruit equals 'plum' change the value to 'strawberry'
I think I can achieve this through using map.
This is what I've tried so far:
const array = [
{
things: [
{ car: 'ford' },
{ colour: 'red' },
{
food: [
{ veg: 'beans' },
{ fruit: 'plum' },
],
},
],
},
{},
{},
]
const newArray = array.map((item) => {
if (item.things.food.fruit === 'plum') return item.things.food.fruit = 'strawberry'
})
CodePudding user response:
You'll need a recursive function that loops over each item in an array. If it encounters an object it will change on of its values if needed or call the function itself again
const array = [
{
things: [
{ car: 'ford' },
{ colour: 'red' },
{
food: [
{ veg: 'beans' },
{ fruit: 'plum' },
],
},
],
},
{},
{},
];
const changePlum = (arr, changeTo = 'strawberry') => (
arr.map(a => {
for (let k in a) {
if (Array.isArray(a[k])) {
a[k] = changePlum(a[k], changeTo);
} else if(a[k] === 'plum') {
a[k] = changeTo;
}
}
return a;
})
)
const res = changePlum(array);
console.log(res);
CodePudding user response:
reformat your data. it will be the best way moving forward.
const array = [
{
car: 'ford',
colour: 'red',
food: {
veg: 'beans',
fruit: 'plum',
},
}
];
this way you can access the data like you want to food.fruit
etc.