我有一个嵌套数组状态,我需要展平。例如:
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}
您需要映射输入数组以创建预期的对象。
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})))
您可以使用一些破坏并构建新对象。
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);
您可以采取以下方法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
中的项目的“形状” - 因此content
和start
字段基于我们从obj
数组的每个nestedArray
中提取的数据。
请注意,这假设id
基于正在处理的index + 1
中项目的当前nestedArray
。
有关.map()
,see this article的更多信息
希望这可以帮助!
只需映射它:
nestedArray.map((a,idx) => ({ id: idx, content: a.obj.fname, start: a.sec.time}))