React / JavaScript:在React中重命名属性时展平嵌套数组

问题描述 投票:-2回答:4

我有一个嵌套数组状态,我需要展平。例如:

nestedArray = [{ name: 'Dog', obj: {fname:'Bigdog'}, sec{time: 15}},
              { name: 'Bird', obj:{fname: Bigbird'}, sec:{time: 23}}]

但是我需要一个看起来像这样的扁平数组:

newArray =[ {id: 1, content: Bigdog, start: 15},
             {id:2, content: Bigbird, start: 23}
javascript reactjs
4个回答
0
投票

您需要映射输入数组以创建预期的对象。

nestedArray = [{
    name: 'Dog',
    obj: {
        fname: 'Bigdog'
    },
    sec: {
        time: 15
    }
}, {
    name: 'Bird',
    obj: {
        fname: 'Bigbird'
    },
    sec: {
        time: 23
    }
}]

console.log(nestedArray.map((ob, index) => ({id: index + 1, content: ob.obj.fname, start: ob.sec.time})))

1
投票

您可以使用一些破坏并构建新对象。

var array = [{ name: 'Dog', obj: { fname: 'Bigdog' }, sec: { time: 15 } }, { name: 'Bird', obj: { fname: 'Bigbird' }, sec: { time: 23 } }],
    result = array.map(({ obj: { fname: content }, sec: { time: start } }, i) =>
        ({ id: i + 1, content, start })
    );
    
console.log(result);

1
投票

您可以采取以下方法using map(),以实现这一目标:

var newArray = nestedArray.map(function(item, index) {

    return {
        id : (index + 1),
        content : item.obj.fname,
        start : item.obj.sec.time
    }
})

这里的基本思想是将每个项目从nestedArray“映射”到新的newArray数组。

当项目被映射时,我们将项目转换为您希望生成的newArray中的项目的“形状” - 因此contentstart字段基于我们从obj数组的每个nestedArray中提取的数据。

请注意,这假设id基于正在处理的index + 1中项目的当前nestedArray

有关.map()see this article的更多信息

希望这可以帮助!


1
投票

只需映射它:

nestedArray.map((a,idx) => ({ id: idx, content: a.obj.fname, start: a.sec.time}))
© www.soinside.com 2019 - 2024. All rights reserved.