You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中根据指定数组键从对象数组提取匹配值的实现问题

提取对象数组指定键生成新数组

需求

有一个对象数组palistarray,需要根据filterkey数组中的键(a、b、c)从每个对象中提取对应键值对,生成仅包含指定键的新对象数组。

原始数据(修正语法错误后)

// 原代码中filterkey的元素需为字符串,否则会被当作未定义变量
var filterkey = ["a","b","c"];
var palistarray = [
    {
        "Id": 199,
        "a": "Rajesh Tamore",
        "b": "23/11/2022",
        "c": "23/11/2022",
        "d": "W"
    },
    {
        "Id": 200,
        "a": "Sunil N",
        "b": "21/11/2022",
        "c": "21/11/2022",
        "d": "S"
    }
];

预期结果

[
    {
        "a": "Rajesh Tamore",
        "b": "23/11/2022",
        "c": "23/11/2022"
    },
    {
        "a": "Sunil N",
        "b": "21/11/2022",
        "c": "21/11/2022"
    }
]

原代码问题

你使用的find方法仅会返回数组中第一个满足条件的元素,并非遍历所有元素;同时用数组元素的index去匹配filterkey的索引,逻辑完全错误,无法实现批量提取指定键的需求。

正确解法

方法一:map + 遍历filterkey构建新对象

const filteredArray = palistarray.map(item => {
    const newObj = {};
    filterkey.forEach(key => {
        // 可选:确保对象存在该键再赋值,避免无意义的undefined
        if (item.hasOwnProperty(key)) {
            newObj[key] = item[key];
        }
    });
    return newObj;
});

console.log(filteredArray);

方法二:map + reduce简化写法

const filteredArray = palistarray.map(item => 
    filterkey.reduce((acc, key) => {
        acc[key] = item[key];
        return acc;
    }, {})
);

console.log(filteredArray);

方法三:ES6解构赋值(固定键场景适用)

如果filterkey的键是固定的a、b、c,可以直接用解构赋值简化代码:

const filteredArray = palistarray.map(({a, b, c}) => ({a, b, c}));

console.log(filteredArray);

内容的提问来源于stack exchange,提问作者Mohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:50:19