[英]How do you iterate over an array of objects to create a new object?
I'm attempting to iterate over a message (which is an array of objects) coming in from a WebSocket connection to create a new object.我正在尝试遍历来自 WebSocket 连接的消息(这是一个对象数组),以创建一个新的 object。 This is the original array:
这是原始数组:
[
{'id': 52, 'tag': 'RFS', 'price': 780},
{'id': 14, 'tag': 'XGH', 'price': 341},
{'id': 29, 'tag': 'LLP', 'price': 997},
]
I'm trying to use this array to create an object using the tag
as the key:我正在尝试使用这个数组来创建一个 object 使用
tag
作为键:
{
'RFS': {'id': 52, 'price': 780},
'XGH': {'id': 14, 'price': 341},
'LLP': {'id': 29, 'price': 997},
}
Let this object = obj
.让这个 object
= obj
。 In Python I'd be able to do something like:在 Python 中,我可以执行以下操作:
>>> new_obj = {i['tag']: {'id': i['id'], 'price': i['price']} for i in obj}
>>> new_obj
{'RFS': {'id': 52, 'price': 780}, 'XGH': {'id': 14, 'price': 341}, 'LLP': {'id': 29, 'price': 997}}
How would I go about doing something like this in JS?我将如何 go 在 JS 中做这样的事情? I've tried experimenting with the
map
function but to no avail.我试过用
map
function 进行试验,但无济于事。 I also attempted to use reduce
:我还尝试使用
reduce
:
var result = obj.reduce(function(new_obj, i) {
new_obj[i.tag] = {'id': i.id, 'price': i.price};
return new_obj;
}, {});
EDIT: The reduce
method above was unsuccessful for me.编辑:上面的
reduce
方法对我来说是不成功的。 I'm probably missing something silly, but console tells me Each child in a list should have a unique "key" prop.
我可能错过了一些愚蠢的东西,但控制台告诉我
Each child in a list should have a unique "key" prop.
, and it returns an undefined
object. ,它返回一个
undefined
的 object。
Here's a solution with reduce
:这是
reduce
的解决方案:
const input = [ {'id': 52, 'tag': 'RFS', 'price': 780}, {'id': 14, 'tag': 'XGH', 'price': 341}, {'id': 29, 'tag': 'LLP', 'price': 997}, ]; const output = input.reduce((acc, obj) => ({...acc, [obj.tag]: { id: obj.id, price: obj.price }}), {}); console.log(output);
Using .reduce
and de-structuring
使用
.reduce
和de-structuring
var data = [ {'id': 52, 'tag': 'RFS', 'price': 780}, {'id': 14, 'tag': 'XGH', 'price': 341}, {'id': 29, 'tag': 'LLP', 'price': 997}, ]; var res= data.reduce((acc, {id, price, tag})=>{ acc[tag] = {id, price}; return acc },{}); console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.