如何将对象列表转换为键控数组/对象?

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

我正在尝试使用Ramda编写代码以仅使用原始对象的idcomment键来产生新的数据结构。我是Ramda的新手,虽然我对使用Python进行类似编码的经验很丰富,但是这给了我一些适合。

给出以下初始数据结构...

const commentData = {
  '30': {'id': 6, 'comment': 'fubar', 'other': 7},
  '34': {'id': 8, 'comment': 'snafu', 'other': 6},
  '37': {'id': 9, 'comment': 'tarfu', 'other': 42}
};

我想把它变成这个…

{
  '6': 'fubar',
  '8': 'snafu',
  '9': 'tarfu'
}

我发现以下要接近的example in the Ramda cookbook

const objFromListWith = R.curry((fn, list) => R.chain(R.zipObj, R.map(fn))(list));
objFromListWith(R.prop('id'), R.values(commentData));

但是它返回的值包括整个原始对象作为值...

{
  6: {id: 6, comment: "fubar", other: 7},
  8: {id: 8, comment: "snafu", other: 6},
  9: {id: 9, comment: "tarfu", other: 42}
}

如何仅将值减小到其comment键的值?

我不需要使用我从菜谱中获得的代码。如果有人可以建议一些可以提供我所期望的结果的代码,也比此处的示例更好(更简单,更短或更有效),我将很乐意使用它。

javascript ramda.js
2个回答
6
投票

[如果您不介意,则不需要使用Ramda,纯JS可以很好地处理它:

您可以使用Object.values()的组合来获取从commentData到动态地将值插入新对象。

.forEach()

但是,如果需要单线,则可以在基于.map()Object.values的情况下从const commentData = { '30': {'id': 6, 'comment': 'fubar', 'other': 7}, '34': {'id': 8, 'comment': 'snafu', 'other': 6}, '37': {'id': 9, 'comment': 'tarfu', 'other': 42} }; let values = Object.values(commentData) let finalObj = {}; values.forEach(x => finalObj[x.id] = x.comment) console.log(finalObj)返回键/值的数组,然后使用Object.fromEntries(),如下所示:

.map()

1
投票

Ramda的单线便是

id
comment

但是,这似乎比epascarello的评论中的建议(稍作调整)干净很多:

const commentData = {
  '30': {'id': 6, 'comment': 'fubar', 'other': 7},
  '34': {'id': 8, 'comment': 'snafu', 'other': 6},
  '37': {'id': 9, 'comment': 'tarfu', 'other': 42}
};

console.log(Object.fromEntries(Object.values(commentData).map(x => [x.id, x.comment])))

或如果不引起任何性能问题,我会写一个类似的版本:

const foo = compose(fromPairs, map(props(['id', 'comment'])), values)

const commentData = {
  '30': {'id': 6, 'comment': 'fubar', 'other': 7},
  '34': {'id': 8, 'comment': 'snafu', 'other': 6},
  '37': {'id': 9, 'comment': 'tarfu', 'other': 42}
}

console .log (
  foo (commentData)
)
© www.soinside.com 2019 - 2024. All rights reserved.