【问题标题】:Mapping specific values of an array of objects to another Object [duplicate]将对象数组的特定值映射到另一个对象[重复]
【发布时间】:2021-07-07 11:22:44
【问题描述】:

如果我有以下两个数组

let first = [
    { name: 'abc', num: 123, isPresent: true }, 
    { name: 'xyz', num: 456, isPresent: false }]

let second = []

如果我需要最终结果看起来像这样,我如何遍历 first 数组并nameisPresent 的值推送到新数组中?

second = [{ name: 'abc', isPresent: true }, {name: 'xyz', isPresent: false }]

【问题讨论】:

    标签: javascript arrays object


    【解决方案1】:

    您可以尝试使用Array.prototype.map() 创建一个新数组,其中填充了在调用数组中的每个元素上调用提供的函数的结果以及Destructuring assignment

    let first = [
        { name: 'abc', num: 123, isPresent: true }, 
        { name: 'xyz', num: 456, isPresent: false }]
    
    let second = first.map(({name, isPresent}) => ({name, isPresent}));
    console.log(second);

    【讨论】:

    • 同一个答案已经有了,为什么还要发帖?
    【解决方案2】:

    您可以使用map 遍历first 数组并仅返回所需的字段。

    let first = [
      { name: "abc", num: 123, isPresent: true },
      { name: "xyz", num: 456, isPresent: false },
    ];
    
    let second = first.map(({ name, isPresent }) => ({ name, isPresent }));
    
    console.log(second);

    【讨论】:

    • @MananSharma 请检查这是否解决了您的问题,如果您遇到任何问题,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多