javascript根据ES6中的单个项目对象数组合并对象数组

时间:2018-06-25 11:59:16

标签: javascript ecmascript-6

我有以下数据

var data = [
  {username:'andy', entries:[{time_in:12, ..},{time_in:334,...}]},
  {username:'andy2', entries:[{time_in:'sr12', ..},{time_in:334,...}]}
]

期待得到的是最终数据

var result = [
  {username:'andy', entry:12},
  {username:'andy', entry:334},
  {username:'andy2', entry:'sr12'},
  {username:'andy2', entry:334},
]

每个数组对象有更多属性,但为简洁起见,我仅包含用户名

所以我尝试过

data.forEach(item=>{
  item.entries.forEach(entry=>{
    //am stuck here
  })
})

5 个答案:

答案 0 :(得分:3)

您可以将array#reducearray#forEach一起使用。遍历每个对象,并针对每个对象遍历entries数组,将新对象添加到累加器中。

const data = [
  {username: 'andy', entries: [{time_in: 12}, {time_in: 334}]},
  {username: 'andy2', entries: [{time_in: 'sr12'}, {time_in: 334}]}
]

const result = data.reduce((r, {username, entries}) => {
  entries.forEach(({time_in: entry}) => r.push({username, entry}))
  return r
}, [])

console.log(result)

答案 1 :(得分:0)

您可以执行以下操作:

const final = [];
data.forEach(item =>
  item.entries.forEach(entry =>
    final.push({ username: item.username, entry: entry.time_in })
  )
);

答案 2 :(得分:0)

我认为map可以解决问题:

var result = data.map((item) => {
    return {
        username: item.username,
        entries: item.entries.length, // Or whatever processing you want
        ...
    }
}

答案 3 :(得分:0)

这是不可变的版本:

const data=[
  {
    username:'andy', entries:[{time_in:12},{time_in:334}]
  }, {
    username:'andy2', entries:[{time_in:'sr12'},{time_in:334}]
  }
];
    

const x = data.reduce((acc, {username, entries}) =>
  acc.concat(
  	entries.map(({time_in}) => ({
        username,
        time_in
    }))
  )
, []);
  
console.log(x);

答案 4 :(得分:0)

可能的解决方案:

const result = data.map(({username, entries}) =>
    entries.map(({time_in})=> ({username: username, entry: time_in}))
).reduce((acc, val) => [...acc, ...val], [])