gpt4 book ai didi

JavaScript将嵌套数组/对象的数组分配为另一个对象的属性

转载 作者:行者123 更新时间:2023-12-03 02:06:08 25 4
gpt4 key购买 nike

我有一个数组,其中包含带有嵌套数组的对象,如下所示:

var category_tree = [
{
category_id: 1,
name: "A",
children: [
{
category_id: 2,
name:" B, child of A",
children: [
{
category_id: 3,
name: "C, child of B",
}
]
}

]
}
]

我想要另一个看起来像这样的对象:

{ 
categories: []
isFetching: false,
isValid: false,
currentFilter: "NAME_ASCENDING",
displayError: false,
errorMessage: ""
}

并设置categories属性等于此category_tree对象。

不幸的是,无论我尝试什么,我都会失去子键按下时的所有内容:

{ 
categories: [{
category_id: 1,
name: "A",
children: []
}],
isFetching: false,
isValid: false,
currentFilter: "NAME_ASCENDING",
displayError: false,
errorMessage: ""
}

这就是我的问题:如何将嵌套数组/对象分配为对象的属性?

编辑:我尝试过的:

let newState = Object.assign({}, state, {                                                 
isFetching: false,
valid: true,
categories: category_tree
})

let newState = Object.assign({}, state, {
isFetching: false,
valid: true
})
newState.categories = category_tree

期望的结果:

{ 
categories: [
{
category_id: 1,
name: "A",
children: [
{
category_id: 2,
name:" B, child of A",
children: [
{
category_id: 3,
name: "C, child of B",
}
]
}

]
}
],
isFetching: false,
isValid: false,
currentFilter: "NAME_ASCENDING",
displayError: false,
errorMessage: ""
}

最佳答案

我已取消删除以表明该切片似乎可以满足您的要求

newCat.categories = category_tree.slice(0);

像这样

var category_tree = [{
category_id: 1,
name: "A",
children: [{
category_id: 2, // added a comma
name: " B, child of A",
children: [{
category_id: 3,
name: "C, child of B",
}]
}

]
}]

var newCat = {
categories: [], // added a comma
isFetching: false,
isValid: false,
currentFilter: "NAME_ASCENDING",
displayError: false,
errorMessage: ""
}

newCat.categories = category_tree.slice(0)

console.log(JSON.stringify(newCat,null, 2));

关于JavaScript将嵌套数组/对象的数组分配为另一个对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49812219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com