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

兰斯·斯隆先生

我正在尝试使用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'
}

接近的Ramda食谱找到了以下示例……

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仅键的值

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

卡尔文·内尼斯(Calvin Nunes)

如果您不介意,则无需使用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()idcomment

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])))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章