stung beet
stung beet

Reputation: 29

Convert structure of array of objects

I have this array of objects:

[{
  "Germany": "text",
  "Brazil": "50.00"
}, {
  "Germany": "1000.00",
  "Brazil": "1100.00"
}, {
  "Germany": "999999999",
  "Brazil": "9999999",
  "France": "12"
}]

I want to convert it to the following structure:

[{
  "name": "Germany",
  "value": 999999999
}, {
  "name": "Brazil",
  "value": 999999999
}, {
  "name": "France",
  "value": 12
}]

Where in the second object we use the higher value for each of the keys in the first object.

Edit: a value could also be text, like "Germany": "text" , in that case that value should be ignored. I added that case in the first object above.

Upvotes: 1

Views: 71

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28434

You can use .reduce to iterate over the objects, and .forEach to iterate over each object entries:

const data = [
  { "Germany": "100.00", "Brazil": "50.00" }, 
  { "Germany": "1000.00", "Brazil": "1100.00" }, 
  { "Germany": "text", "Brazil": "9999999", "France": "12" }
];

const res = Object.values(data.reduce((acc,item) => {
  Object.entries(item).forEach(([name,value]) => {
    if(!isNaN(value)) {
      const prev = acc[name];
      if(!prev) acc[name] = { name,value } ;
      else if(prev.value < value) prev.value = value;
    }
  });
  return acc;
}, {}));

console.log(res);

Upvotes: 3

Rajneesh
Rajneesh

Reputation: 5318

You can make use of reduce function to get your expected output. Inside reduce, you can take the Object.entries of the current object in order to group by the country name.

const arr = [{
  "Germany": "100.00",
  "Brazil": "50.00"
}, {
  "Germany": "1000.00",
  "Brazil": "1100.00"
}, {
  "Germany": "999999999",
  "Brazil": "9999999",
  "France": "12"
}];

const result = Object.values(arr.reduce((a,e)=>{
    Object.entries(e).forEach(([name, value])=>{
        a[name] ??= {name, value:0};
        a[name].value = a[name].value>value ? a[name].value : value
    });
    return a;
},{}));

console.log(result);

Upvotes: 4

Related Questions