jquery将对象项目推送到数组

时间:2018-01-05 21:24:02

标签: javascript jquery

我可以转换它:

var arr = [{"1":["34"]},{"2":["32","31","30"]},{"3":["29","28","27","26"]}]

到此:

{"1":["34"],"2":["32","31","30"],"3":["29","28","27","26"]}

jQuery中是否有函数可以执行此操作?

3 个答案:

答案 0 :(得分:0)

您可以将Object.assignspread syntax ...一起使用。

var array = [{ 1: ["34"] }, { 2: ["32", "31", "30"] }, { 3: ["29", "28", "27", "26"] }],
    object = Object.assign({}, ...array);
    
console.log(object)

答案 1 :(得分:0)

或者你可以用“旧式”来做:

var src = [{"1":["34"]},{"2":["32","31","30"]},
      {"3":["29","28","27","26"]}], trg = {};

src.forEach((e)=>{for(var p in e) trg[p]=e[p];});

答案 2 :(得分:-1)

 arr.reduce((obj, arrayElem) => Object.assign(obj, arrayElem), {})

通过将所有对象分配在一起来减少数组。或者:

 Object.assign({}, ...arr)