gpt4 book ai didi

javascript - 如何同时合并和平展数组

转载 作者:太空宇宙 更新时间:2023-11-04 16:08:07 25 4
gpt4 key购买 nike

我有两个数据数组,一个具有树结构,另一个只是一个包含详细信息的嵌套数组..

我现在想做的是展平这个详细信息数组并将其合并到树的结构中。

详细信息和树都具有具有相同唯一 ID 的记录。

   var tree = [{
"Children": [{
"Children": [],
"ID": "1",
"PendingChange": true,
}],
"ID": "22",
"PendingChange": false,
}];

var details = [{
"Address": {
"Jurisdiction": {
"Name": "United Kingdom"
},
"City": "Waltham Cross"
},
"ID": "1",
"Name": "J"
}];



var finalArray = _.map(tree, function(e) {
return _.extend(e, _.omit(_.findWhere(details, {
ID: e.ID
}), 'ID'));
});

console.log(finalArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

所需输出

   var tree = [{
"Children": [{
"Children": [],
"ID": "1",
"PendingChange": true,
"Name": "J"
"Address_City": "Waltham Cross"
"Address_Jurisdiction_Name": "United Kingdom"
}],
"ID": "22",
"PendingChange": false,
}];

下划线不是必须的,我只是坚持使用它 - https://jsfiddle.net/ey8hqn19/

最佳答案

您可以使用 for...in 循环创建递归函数,该函数将循环深层树对象,然后使用 find 详细查找具有相同 id 的对象并添加属性.

var tree = [{
"Children": [{
"Children": [],
"ID": "1",
"PendingChange": true,
}],
"ID": "22",
"PendingChange": false,
}];

var details = [{
"Address": {
"Jurisdiction": {
"Name": "United Kingdom"
},
"City": "Waltham Cross"
},
"ID": "1",
"Name": "J"
}];

function makeTree(data) {
for (var i in data) {
if (typeof data[i] == 'object') makeTree(data[i])
if (i == 'ID') {
var f = details.find(function(e) {
return e.ID == data[i]
})
if (f) {
Object.assign(data, {
"Name": f.Name,
"Address_City": f.Address.City,
"Address_Jurisdiction_Name": f.Address.Jurisdiction.Name
})
}
}
}
}

makeTree(tree)
console.log(tree)

关于javascript - 如何同时合并和平展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41718952/

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