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

如何将JS对象数组转换为仅保留内部newValues子对象的数组?

提取数组对象中newValues属性生成新数组

直接用Array.map()遍历原数组,每个元素只保留newValues对应的对象即可,代码非常简洁:

// 原数组
let result = [
    {
        "a": 1,
        "b": 2,
        "c": 3,
        "newValues": {
            "a": 10,
            "b": 20,
            "c": 30
        }
    },
    {
        "d": 4,
        "e": 5,
        "f": 6,
        "newValues": {
            "d": 40,
            "e": 50,
            "f": 60
        }
    }
];

// 转换代码
const transformedResult = result.map(item => item.newValues);

// 输出结果和预期完全一致
console.log(transformedResult);

额外处理:避免newValues不存在的情况

如果原数组中可能存在没有newValues属性的元素,可以加个默认值防止报错:

const transformedResult = result.map(item => item.newValues || {});

这样即使某个元素没有newValues,也会返回一个空对象,不会导致程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:01:33