gpt4 book ai didi

javascript - JS ES6 按键数组过滤对象的正确方法

转载 作者:行者123 更新时间:2023-11-30 13:51:58 30 4
gpt4 key购买 nike

我想获取一个对象数组并过滤每个对象以仅返回键与数组中的项目匹配的属性。

例如:

const myKeys    = ['key_1', 'key_3'];
const myArray = [
{
key_1: 'Some Value A',
key_2: 'Some Other Value A',
key_3: 'Some Final Value A',
},
{
key_1: 'Some Value B',
key_2: 'Some Other Value B',
key_3: 'Some Final Value B',
},
{
key_1: 'Some Value C',
key_2: 'Some Other Value C',
key_3: 'Some Final Value C',
},
];

应该产生以下结果:

const result   = [
{
key_1: 'Some Value A',
key_3: 'Some Final Value A',
},
{
key_1: 'Some Value B',
key_3: 'Some Final Value B',
},
{
key_1: 'Some Value C',
key_3: 'Some Final Value C',
},
];

我相信这应该可以通过 .map().filter() 的组合来实现,但我不确定如何最好地实现以下等价物使用 ES6:

const filteredData = (array, keys) => {
const newArr = [];

for (let i = 0; i < myArray.length; i++) {
const item = myArray[i];
let newObj = {};

for (let j = 0; j < myKeys.length; j++) {
const filter = myKeys[j];
newObj[filter] = item[filter];
}

newArr.push(newObj);
}

return newArr;
}

console.log(filteredData(myArray, myKeys));

最佳答案

您可以映射 wnated 条目并使用它构建对象。

const 
keys = ['key_1', 'key_3'],
data = [{ key_1: 'Some Value A', key_2: 'Some Other Value A', key_3: 'Some Final Value A' }, { key_1: 'Some Value B', key_2: 'Some Other Value B', key_3: 'Some Final Value B' }, { key_1: 'Some Value C', key_2: 'Some Other Value C', key_3: 'Some Final Value C' }],
result = data.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - JS ES6 按键数组过滤对象的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58062707/

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