简体   繁体   中英

How to add a child array to a parent array in javascript?

I have a list of objects from a table that are returned from an http post method in my angular service. I need to parse out the data so that it makes sense.

I have an array of Headers that has a title and a description. I want to add a child array to each header that has all of the rows that are affected by this description. How can I do this in javascript/angular 2?

So it would look like this

Header {Title, Error Description 1 }
     - Object 1 {ColumnId, Date, Column Description }
     - Object 2 {ColumnId, Date, Column Description }
Header 2 {Title, Error Description 2}
      - Object 1 {ColumnId, Date, Column Description }
     -  Object 2 {ColumnId, Date, Column Description }

There are not enough details in your request, but I would do the following:

let resultList = headerList.map(headerItem => Object.assign(headerItem, {
  descriptionList: getDescriptionList(headerItem)
}));

Assumptions:

  • headerList is the initial list of Header objects;

  • descriptionList is the name of the property where the child list should be present;

  • getDescriptionList(headerItem) is the child list getter method based on initial Header object data, something like

It's just a fantasy and I need more details on the lists build process, but the child list generator could look like:

const getDescriptionList = (headerItem) => {
  return [{
      columnId: "001",
      date: new Date(),
      columnDescription: getDesc(headerItem, 1)
    }, {
      columnId: "002",
      date: new Date(),
      columnDescription: getDesc(headerItem, 2)
    }, 
    // ...
  ];
}

Here is another assumption:

  • getDesc(item, columnIndex) is the column description getter method based on initial Header object data and column index

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