如何在其他数组中过滤/减少具有特定动态键的对象数组



我要解释我的问题。我没有时间去想更多,我有一个拦网手,我想不出来,所以任何帮助都将不胜感激。例如,我有一个对象数组(它可以是具有100+个元素的数组(:

const arr = [
{ value: '1', id: 1, number: 1, other: 'example', data: '6' },
{ value: '2', id: 2, number: 2, other: 'example', data: '7' },
{ value: '3', id: 3, number: 3, other: 'example', data: '8' },
{ value: '4', id: 4, number: 4, other: 'example', data: '9' },
{ value: '5', id: 5, number: 4, other: 'example', data: '10' },
];

在另一个数组中,我有包含特定密钥的字符串,比如:

const keys = ['value', 'id', 'number'];

我的问题是我想返回变量CCD_ 1只包含基于CCD_。类似的东西:

const arr = [
{ value: '1', id: 1, number: 1 },
{ value: '2', id: 2, number: 2 },
{ value: '3', id: 3, number: 3 },
{ value: '4', id: 4, number: 4 },
{ value: '5', id: 5, number: 4 },
];

我希望它是动态的,因为keys变量中的值不是恒定的,可以是valueotherdata,也可以只是dataidother等。

创建一个基于键数组返回的函数,并使用该函数进行映射。。

const arr = [
{ value: '1', id: 1, number: 1, other: 'example', data: '6' },
{ value: '2', id: 2, number: 2, other: 'example', data: '7' },
{ value: '3', id: 3, number: 3, other: 'example', data: '8' },
{ value: '4', id: 4, number: 4, other: 'example', data: '9' },
{ value: '5', id: 5, number: 4, other: 'example', data: '10' },
];
const keys = ['value', 'id', 'number'];
function pick(obj, keys){
let result = {};
for(let i=0; i<keys.length; i++){
result[keys[i]] = obj[keys[i]];
}
return result;
}
let finalArr = arr.map( value => pick(value,keys));
console.log(finalArr);

您可以使用arr0和reduce来完成此操作。

const arr = [
{ value: '1', id: 1, number: 1, other: 'example', data: '6' },
{ value: '2', id: 2, number: 2, other: 'example', data: '7' },
{ value: '3', id: 3, number: 3, other: 'example', data: '8' },
{ value: '4', id: 4, number: 4, other: 'example', data: '9' },
{ value: '5', id: 5, number: 4, other: 'example', data: '10' },
];
const keys = ['value', 'id', 'number'];
const res = arr.map(item => keys.reduce((acc, key) => ({...acc, [key]: item[key]}), {}));
console.log(res);
.as-console-wrapper{min-height: 100% !important; top: 0;}

最新更新