gpt4 book ai didi

javascript - 当数组包含嵌套对象数组内的输入值时获取对象

转载 作者:行者123 更新时间:2023-11-28 16:41:53 24 4
gpt4 key购买 nike

这是我正在处理的对象的嵌套数组:

let arrayOfElements = 
[
{
"username": "a",
"attributes":
{
roles:["Tenant-Hyd"],
groups:["InspectorIP", "InspectorFT"]
}
},
{
"username": "b",
"attributes":
{
roles:["Tenant-Pune"],
groups:["InspectorIP"]
}
},
{
"username": "c",
"attributes":
{
roles:["Tenant-Hyd"],
groups:["InspectorIP"]
}
}
];

我希望用户如果具有 Tenant-hyd Angular 色,并且如果组具有多个字符串,那么用户应该吐出两个。所以最终的输出应该是:

arrayOfElements=[
{
"username": "a",
groups:"InspectorIP"
},
{
"username": "a",
groups:"InspectorFT"
},
{
"username": "c",

groups:"InspectorIP"

}
];

最佳答案

我将在这里使用 filterreduce 数组函数的组合。

filter 将删除 attributes.roles 不包含 'Tenant-Hyd' 的所有元素。

reduce 然后会展平 groups 数组。

const arrayOfElements = 
[
{
"username": "a",
"attributes":
{
roles:["Tenant-Hyd"],
groups:["InspectorIP", "InspectorFT"]
}
},
{
"username": "b",
"attributes":
{
roles:["Tenant-Pune"],
groups:["InspectorIP"]
}
},
{
"username": "c",
"attributes":
{
roles:["Tenant-Hyd"],
groups:["InspectorIP"]
}
}
];

const filtered = arrayOfElements.filter(x => x.attributes.roles.includes('Tenant-Hyd'));

console.log('filtered', filtered);

const flattened = filtered.reduce((arr, current) => {
// create a new object for each group with the current username
const groups = current.attributes.groups.map(group => ({
username: current.username,
groups: group
}));
// push the new objects into the array
arr.push(...groups);
// return the array to the next iteration
return arr;
}, []);

console.log('flattened', flattened);

此演示设置初始数组,运行过滤器,然后运行reduce。我已将这些步骤分开,以便您可以看到每个阶段发生的情况,但您可以轻松地将它们组合起来。

const result = arrayOfElements
.filter(x => x.attributes.roles.includes('Tenant-Hyd'))
.reduce((arr, current) => {
arr.push(...current.attributes.groups.map(group => ({
username: current.username,
groups: group
})));
return arr;
}, []);

归约函数

reduce数组函数接受回调和初始值。我传递一个空数组作为初始值。

这确实是一个更强大的 map 。将迭代源数组,并在每次迭代时调用回调。回调返回的值将用作下一次迭代的累加器。

// declare the callback
const callback = (arr, current) => {
// arr is the initial value on the first loop
// and whatever we return from this callback on subsequent loops

// add our flattened items to the accumulated array
arr.push(...current.attributes.groups.map(group => ({
username: current.username,
groups: group
})));

// return the accumulated array to the next iteration
return arr;
};

// loop over the items in myArray, calling the callback for each item
// pass an empty array in as the accumulator
myArray.reduce(callback, []);

一个更简单的替代方案是这样的:

const arr = [];
myArray.forEach(current => {
arr.push(...current.attributes.groups.map(group => ({
username: current.username,
groups: group
})));
});

这更容易理解,但不如使用reduce那么简洁。

关于javascript - 当数组包含嵌套对象数组内的输入值时获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61074900/

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