Javascript复制对象数组中的嵌套数组

时间:2018-03-04 23:09:04

标签: javascript arrays object

我有以下状态对象。

 list: [
      {
        "_id":"1","category":"Cat 1",
        "subcategory":[
          {"_id":"2","subcat":"Subcat 1"},
        ]
      },
      {"_id":"2","category":"Cat 2"},
    ],

我想修改_id:1的值。我使用我需要的对象的副本:

let listCopy = list.filter(el => el._id == 1)

然后:

let subList = listCopy.subcategory.slice();

为什么我一直未定义subList?制作嵌套对象的副本有哪些选项?

2 个答案:

答案 0 :(得分:3)

filter方法返回一个数组,你期望一个对象。如果您只想要一个元素,可以尝试listCopy[0].subcategory.slice();

答案 1 :(得分:0)

结果是一个数组,因此您需要:listCopy[0]....

var list = [
      {
        "_id":"1",
        "category":"Cat 1",
        "subcategory":[
          {"_id":"2","subcat":"Subcat 1"},
        ]
      },
      {"_id":"2",
       "category":"Cat 2"
      }
    ];

let listCopy = list.filter(el => el._id == 1)  // Result is an array
let subList = listCopy[0].subcategory.slice(); // <-- Need to use index
console.log(subList);