简体   繁体   English

转换对象数组的结构

[英]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.在第二个 object 中,我们为第一个 object 中的每个键使用较高的值。

Edit: a value could also be text, like "Germany": "text" , in that case that value should be ignored.编辑:一个值也可以是文本,比如"Germany": "text" ,在这种情况下应该忽略该值。 I added that case in the first object above.我在上面的第一个 object 中添加了该案例。

You can make use of reduce function to get your expected output.您可以使用reduce function 来获得您预期的 output。 Inside reduce, you can take the Object.entries of the current object in order to group by the country name.在reduce里面,你可以拿当前Object.entries的Object.entries来按国家名称分组。

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

You can use .reduce to iterate over the objects, and .forEach to iterate over each object entries:您可以使用.reduce迭代对象,并.forEach迭代每个 object 条目:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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