简体   繁体   中英

How to get more than one property and push json object into an array?

I have this programs array of object which returns me the category id and the category name:

{
  categoryId: 101
  categoryName: "category name 1"
},
{
  categoryId: 102
  categoryName: "category name 2"
}

Using the below logic I was only storing category name into my categories array, but now I also only want to store category id into my array as a JSON object.

let categories = [];
_.map(programs, prog => {
  if(prog.subapplicationFlag === true && !categories.includes(prog.categoryName)) {
    return categories.push(prog.categoryName)
  }
})

can someone please help me with the solution to have the following array instead?

desired output:

categories array:

[
  {
    categoryId: 101
    categoryName: "category name 1"
  },
  {
    categoryId: 102
    categoryName: "category name 2"
  },
  {
    ... and so on
  },
]

Your block of code is pushing prog.categoryName into the categories array.

let categories = [];
_.map(programs, prog => {
  if(prog.subapplicationFlag === true && !categories.includes(prog.categoryName)) {
    return categories.push(prog.categoryName)
  }
})

Edit:

To return both the categoryName and categoryId, you can do return categories.push({categoryName: prog.categoryName, categoryId: prog.categoryId})

This will push an object into your category array.

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