合并其父母具有可变键名的js对象

时间:2019-05-01 09:40:36

标签: javascript arrays

我有一个具有以下结构的对象:

mymain = { 
name1: [ {key1: number, key2: "string"},{key1: number, key2: "string"} ],
name2: [ {key1: number, key2: "string"},{key1: number, key2: "string"} ],
name3: [ {key1: number, key2: "string"},{key1: number, key2: "string"} ]
}

顶级项(名称1,名称2,名称3)的数量和键名会有所不同。

我想将所有对象(数量和值也可变,但都具有相同的键结构)在这些名称下合并为一个大对象,如下所示:

Allconcat = [{key1: number, key2: "string"},{key1: number, key2: "string"},{key1: number, key2: "string"},{key1: number, key2: "string"},{key1: number, key2: "string"},{key1: number, key2: "string"}]

我尝试提取顶级项目的名称,然后将它们循环以连接对象,但这给出了错误的项目数:

var names = Object.keys(mymain)
    var firstname = names[0]
    names.shift() // should remove first item
    var firstObj = mymain[firstname] // name1 object
    var Allconcat
    console.log(firstObj) // correctly shows name1 with 2 keys
    for (var r = 0, rlen = names.length; r < rlen; r++) {
      Allconcat = firstObj.concat(mymain[names[r]])
    }
    console.log(Allconcat) // shows 4 objects, missing 2 in the middle, first and last are there

转移或不转移都没有什么区别,而且我总是最终在中间缺少一些元素。

1 个答案:

答案 0 :(得分:2)

一种选择是获取Object.values对象的mymain,并展平数组:

const mymain = { 
  name1: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ],
  name2: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ],
  name3: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ]
};

const Allconcat = Object.values(mymain).flat();
console.log(Allconcat);

或者,如果您不能使用.flat(),请传播到concat中:

const mymain = { 
  name1: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ],
  name2: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ],
  name3: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ]
};

const Allconcat = [].concat(...Object.values(mymain));
console.log(Allconcat);