简体   繁体   中英

How to copy values from parent to children in array

I have an array with some names as below:

[ 
  {
    name: "John",
    lastName: "Doe",
    children: [
       {
          name: "Max",
          lastName: ""
       },
       {
          name: "Jay",
          lastName: ""
       },
    ]
  },
  {
     ...
  }
]

So I have an array with users - some of them have children. The users on top level have a lastName property. I want to copy this value to their children.

Is this possible by doing a remapping?

I am struggling on how to correctly updating the data with values from their "parents".

you could do nested mapping that creates a new array of parents:

arr.map(parent => ({
  ...parent, // (1)
  children: item.children?.map(child => ({
    ...child, // (2)
    lastName: parent.lastName, // (3)
  })
);

(1) copies all props of each parent but assigns a new array of children that is the result of map method on children.

(2) copies all props of each child into the new children array

(3) assign the lastName of the parent

 const data = [ { name: "John", lastName: "Doe", children: [ { name: "Max", lastName: "" }, { name: "Jay", lastName: "" } ] } ]; const findNames = () => { return data.reduce((res, curr) => { const { children = [], lastName = "" } = curr; const childrenWithName = children.map((v) => ({...v, lastName: lastName })); return [...res, {...curr, children: childrenWithName }]; }, []); }; const res = findNames(data); console.log(res);

Or you can view solution in sandbox with types

This isn't really a Typescript problem, as much as it is a Javascript problem. Unless you are asking how to model the type of that.

But the code should be pretty simple. Loop over elements in the array, if the children property is not undefined, loop over it, and set the last name to the parent last name. Pseudo code:

For each parent
     If children != undefined
           For each child
               child.LastName = parent.LastName 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM