将对象数组设置为具有选定ID的对象,并使用数组的相同键设置对象?

时间:2019-07-20 18:11:53

标签: javascript

我很难为此解决方案,所以我有很多对象,例如:

const objectsArr = [
  { commment: 'hello world', bookId: '1'},
  { commment: 'foo world', bookId: '2'},
  { commment: 'bar world', bookId: '1'},
  { commment: 'bazz world', bookId: '2'},
]

您看到我有一个外键bookId,我希望它成为注释数组的键,我想将其转换为以下形式:

const objectBookIdKey = {
  1: [{ commment: 'hello world', bookId: '1'}, { commment: 'bar world', bookId: '1'}],
  2: [{ commment: 'foo world', bookId: '2'},{ commment: 'bazz world', bookId: '2'}],
}

我在上面创建的要使用bookId属性的对象,并且具有与相同bookId相同的对象数组,对此我知道lodash,ramda,但是我想在js中进行学习。我只是不知道该怎么做。帮助吗?

2 个答案:

答案 0 :(得分:1)

您可以使用reduce

  • 遍历LimitedNamedServer
  • 使用objectsArr作为密钥
  • 检查它是否已经存在于对象上,如果未分配默认值,则推送该值,否则将其推送到现有的对象上

bookId

答案 1 :(得分:1)

使用reduce()bookId进行分组

const objectsArr = [
    { commment: 'hello world', bookId: '1'},
    { commment: 'foo world', bookId: '2'},
    { commment: 'bar world', bookId: '1'},
    { commment: 'bazz world', bookId: '2'},
]

const result = objectsArr.reduce((old, cur) => {
    if (old[cur.bookId]) old[cur.bookId].push(cur)
    else old[cur.bookId] = [cur]
    return old
}, {})

console.log(result)