简体   繁体   中英

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. 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:

{
  'RFS': {'id': 52, 'price': 780},
  'XGH': {'id': 14, 'price': 341},
  'LLP': {'id': 29, 'price': 997},
}

Let this object = obj . In Python I'd be able to do something like:

>>> 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? I've tried experimenting with the map function but to no avail. I also attempted to use 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. I'm probably missing something silly, but console tells me Each child in a list should have a unique "key" prop. , and it returns an undefined object.

Here's a solution with 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

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM