我想获取一个对象数组并过滤每个对象,以仅返回键与数组中的某个项目匹配的属性。
例如:
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));
答案 0 :(得分:2)
您可以映射所拥有的条目并使用它来构建对象。
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; }
答案 1 :(得分:0)
您可以简单地遍历keys
并构建一个仅包含这些键和相应值的新对象
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',},];
let final = myArray.map(v => {
return myKeys.reduce((op, key) => {
op[key] = v[key]
return op
}, {})
})
console.log(final)
答案 2 :(得分:0)
<=120
答案 3 :(得分:0)
您可以将每个对象.map
移至其条目,以便可以.filter
移出任何myKeys
中没有键的条目,然后使用.fromEntries()
进行构建像这样设置新对象:
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 res = myArray.map(obj => Object.fromEntries(Object.entries(obj).filter(([k, v]) => myKeys.includes(k))));
console.log(res);