如何将数组添加到数组对象

时间:2019-07-25 14:46:07

标签: javascript arrays json api object

如何使object1object2?这是API的JSON类型,因此我不能只是手动将array的值放入对象中。 Z实际上是var z = [4,5,6];一个完全独立的数组。

var object1  = {
  value:[{
    "x": "apple",
    "y": [1,2,3]
 }]
};

var object2 = {
  value:[{
    "x": "apple",
    "y": [1,2,3],
    "z": [4,5,6]
  }]
};

2 个答案:

答案 0 :(得分:1)

您可以访问阵列并对其进行更新:

const updateObjectAtIndex = (arr, index, newData) => {
  const clone = [...arr];
  const result = {
    ...clone[index],
    ...newData
  };
  
  clone[index] = result;
  
  return clone;
}

var object1  = {
  value:[{
    "x": "apple",
    "y": [1,2,3]
 }]
};

var object2 = {
  ...object1,
  value: updateObjectAtIndex(object1.value, 0, {z: [4, 5, 6]})
}

console.dir(object2)

答案 1 :(得分:0)

  

Object.assign()方法用于复制所有值   从一个或多个源对象到目标的可枚举的自身属性   宾语。它将返回目标对象。

var object1  = {
  value:[{
    "x": "apple",
    "y": [1,2,3]
 }]
};

var object2 = {
  value:[{
    "x": "apple",
    "y": [1,2,3],
    "z": [4,5,6]
  }]
};

const object3 = Object.assign(object1, object2);

console.log(object3);