我有以下状态对象。
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?制作嵌套对象的副本有哪些选项?
filter方法返回一个数组,你期望一个对象。如果你只想要一个元素,你可以试试listCopy[0].subcategory.slice();
。
结果是一个数组,所以你需要: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);