我正在尝试使用Ramda编写代码,以仅使用原始对象的id
和comment
键来生成新的数据结构。我是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'
}
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
仅键的值?
我不需要使用从食谱中获得的代码。如果有人可以建议一些可以提供我所期望的结果的代码,也比这里的示例更好(更简单,更短或更有效),我将很乐意使用它。
如果您不介意,则无需使用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()
id
comment
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] 删除。
我来说两句