简体   繁体   中英

Merge javascript objects in an array based on an array inside it

What is the best way to reorganize array into output? I need to merge all value keys (whether array or not) into objects sharing the same name key. There is something similar here, but that doesn't answer my question because I have arrays as well.

var array = [{
  VULN: [{random1:"asd11",random2:"asd12"}, {random3:"asd23",random4:"asd24"}]
}, {
  VULN: [{random5:"asd35",random6:"asd36"}, {random7:"asd47",random8:"asd43"}]
}, {
  VULN: [{random9:"asd55",random10:"asd51"}, {random11:"asd56",random12:"asd63"}]
}];

to

VULN=[{random1:"asd11",random2:"asd12"}, {random3:"asd23",random4:"asd24"},{name:"asd3",value:"asd3"}, {random5:"asd35",random6:"asd36"}, {random7:"asd47",random8:"asd43"}, {random9:"asd55",random10:"asd51"}, {random11:"asd56",random12:"asd63"}]

Here is what you want:

 var array = [{ VULN: [{ name: "asd1", value: "asd1" }, { name: "asd2", value: "asd2" }] }, { VULN: [{ name: "asd3", value: "asd3" }, { name: "asd4", value: "asd4" }] }, { VULN: [{ name: "asd5", value: "asd5" }, { name: "asd6", value: "asd6" }] }]; console.log(array.map(x => x.VULN).flat())

Use flatMap :

array.flatMap(x => x.VULN);

Use lodash

lodash.flatten(array.map(x => x.VULN))

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