gpt4 book ai didi

javascript - 从字符串键检索和连接深度嵌套数组的递归方法

转载 作者:行者123 更新时间:2023-12-03 05:28:46 24 4
gpt4 key购买 nike

我试图获取一个带有嵌套数组的对象,给它们一个字符串键并返回一个连接值的数组,所以:

假设我有以下数据:

let data = {
artists: [{
name: "Foo",
concerts: [{
arena: "Wembley",
city: "London"
}, {
arena: "NEC",
city: "Birmingham"
}]
}, {
name: "Bar",
concerts: [{
arena: "Madison Square Garden",
city: "New York"
}, {
arena: "Kodak Theatre",
city: "Los Angeles"
}]
}]
}

我希望能够传递以下字符串:

artists.concerts.arena

并让它为每个对象返回一个包含 arena 中所有值的数组,所以在本例中我想要:

["Wembly", "NEC", "Madison Square Garden", "Kodak Theatre"]

我遇到的困难是递归元素,我认为我只是没有正确设置和返回值,或者我错误地调用了递归元素,这是(非常粗糙的)代码:

function getValueByStringPath(path, data) {

path = (Array.isArray(path)) ? path : path.split(".");

// Loop through the path
for (var i = 0; i < path.length; i++) {
if (Array.isArray(data)) {
let vals = [];
// We have an array, so lets loop through it
for (var j = 0; j < data.length; j++) {
// if we have more properties so get them
if (path.length - 1 > i) {
vals = getValueByStringPath(path[i + 1], data[j][path[i]])
} else {
vals.push(data[j][path[i]]);
}
}

return vals;

} else {
data = data[path[i]];
}
}

return (Array.isArray(data)) ? data : [data];
}

这是一个 JSFiddle:https://jsfiddle.net/p0eadu5h/

最佳答案

您可以使用嵌套的for..of循环来返回预期结果

let data = {
artists: [{
name: "Foo",
concerts: [{
arena: "Wembley",
city: "London"
}, {
arena: "NEC",
city: "Birmingham"
}]
}, {
name: "Bar",
concerts: [{
arena: "Madison Square Garden",
city: "New York"
}, {
arena: "Kodak Theatre",
city: "Los Angeles"
}]
}]
}

let res = [];
for (let {concerts} of data.artists) {
for (let {arena} of concerts) {
res = [...res, arena]
}
}

console.log(res);

关于javascript - 从字符串键检索和连接深度嵌套数组的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41044108/

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