Home > Enterprise >  Nested Object destructuring within array
Nested Object destructuring within array

Time:03-09

I have a situation with a pretty complex object. I want to change one of the fields within an object inside an array inside a larger object:

here is the context:

const bigObject ={id:1, obj1:{arr:[
    {id:2, name:”suzy”},
    {id:3, name:”littleFinger”},
    {id:4, name:”dragon”},
]}}

this is what I've done so far:

const changeName = (param)=>{
    const newName ='John'
    const {obj1}= param
    const newNames = obj1.arr.map(names=>{
        return {...names, name:newName}
    })
    return {...param, param.obj1 : newNames }
}

I know this is wrong, but I don't know how to change the obj1 in the param.

return {...param, param.obj1 : newName }

expected functionality should be:

const newItem = changeName(bigObject)

result:  newItem = {id:1, obj1:{arr:[
    {id:2, name:”John”},
    {id:3, name:”John”},
    {id:4, name:”John”},
]}}

Any ideas? Thanks!

CodePudding user response:

I'm not so sure a function is such a good idea here, because you have a lot of hardcoded values, like obj1, arr and "John". That makes it too specific.

Here is how you would create a new object with the name string replaced with "John":

const bigObject = {
    id: 1,
    obj1: {
        arr: [
            { id: 2, name: "suzy" },
            { id: 3, name: "littleFinger" },
            { id: 4, name: "dragon" },
        ]
    }
};

const result = {
    ...bigObject,
    obj1: {
        ...bigObject.obj1,
        arr: bigObject.obj1.arr.map(item => ({
            ...item,
            name: "John"
        }))
    }
};

console.log(result);

You can of course put this in a function, but then I would suggest you make it more generic, so you don't have to put hard-coded names/strings in your code there.

CodePudding user response:

Declaring bigObject and newName

const bigObject = {
    id: 1,
    obj1: {
        arr: [
            { id: 2, name: "suzy" },
            { id: 3, name: "littleFinger" },
            { id: 4, name: "dragon" },
        ]
    }
}
const newName = "John";
  1. Impure function (Mutates the original bigObject)
const changeName = (bigObject, newName) => { 
    bigObject.obj1.arr.forEach(v => v.name = newName);
}
  1. Pure function (does not mutate the original bigObject)
const changeName = (bigObject, newName) => {
    const newArr = bigObject.obj1.arr.map(v => ({ ...v, name: newName }));
    return { ...bigObject, obj1: { arr: newArr } };
}
  • Related