gpt4 book ai didi

javascript - 根据同级的现有属性将新属性添加到 javascript 对象中

转载 作者:行者123 更新时间:2023-11-28 07:11:50 25 4
gpt4 key购买 nike

假设我有一个像这样的复杂对象数组:

[
{
"title": "Fundamentals",
"order": 1,
"lessonRef": "fundamentals",
"children": [
{
"title": "History",
"order": 1,
"lessonRef": "history",
"children": []
},
{
"title": "NEW NODE 1",
"lessonRef": "NEW NODE 1 STUB",
"children": []
},
{
"title": "Math",
"order": 2,
"lessonRef": "math",
"children": []
},
{
"title": "NEW NODE 2",
"lessonRef": "NEW NODE 2 STUB",
"children": []
}
{
"title": "Geography",
"order": 3,
"lessonRef": "geography",
"children": []
}
]
},
{
"title": "Basics",
"order": 2,
"lessonRef": "basics",
"children": []
}
]

我该怎么办:

  1. 迭代每个节点,
  2. 检测到存在一个没有 order 字段的新节点,并根据它在数组中的位置为其指定下一个数字,
  3. 然后增加每个现有的同级,同时也
  4. 考虑到其下面任何其他新添加的节点吗?

在我开始使用纯 JavaScript 之前,我正在寻找一种 lodash 方法来帮助我开始。

编辑:提供了我的解决方案——在我的例子中,数组顺序是有保证的,但我会将问题扩展到不保证顺序的情况。

最佳答案

如果这是你想做的:

var yourArray = yourDataArr
var arr1 = []


//fix children first
_.each(yourArray, function(item) {
if(item.children) item.chilren = fixArr(children)
arr1.push(item)
})


//fix your array
yourArray = fixArr(arr1)


//fix function
function fixArr(arr) {

var res = []
var prevOrder

_.each(arr, function(item) {


var currentOrder = item.order

if(!currentOrder) {
item.order = prevOrder?prevOrder + 1:1
prevOrder = item.order + 0
}
res.push(item)

})

return res

}

//or maybe this is you want
function fixArrAlt(arr) {

var res = []
var order = 1

_.each(arr, function(item) {

item.order = order + 0
res.push(item)
order ++

})

return res

}

关于javascript - 根据同级的现有属性将新属性添加到 javascript 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227499/

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