简体   繁体   English

在数组json中的单个对象中转换多个相同的键对象

[英]Converting multiple same key object in single object within array json

I have this json below:我在下面有这个json

[
  {"animal": "cat"},
  {"animal": "dog"},
  {"animal": "elephant"},
  {"vehicle": "car"},
  {"vehicle": "bike"},
  {"vehicle": "truck"},
  {"toys": "a1"},
  {"toys": "a2"},
  {"toys": "a3"}
]

My expected json response is:我预期的 json 响应是:

[
  {"animal": "cat", "vechile": "car", "toys": "a1"},
  {"animal": "dog", "vechile": "bike", "toys": "a2"},
  {"animal": "elephant", "vechile": "truck", "toys": "a3"}
]

I tried the following program but didn't give me the expected output, I wanted to make an array where I could compare it and add accordingly:我尝试了以下程序,但没有给我预期的输出,我想制作一个可以比较的数组并相应地添加:

var myGlobalArr = []
var globalObject = {}

for (var i = 0; i < mainArr.length; i++)
{
    if (Object.keys(mainArr[i])[0] == Object.keys(myGlobalArr[i])[0])
    {
        globalObject[Object.keys(mainArr[i])[0]] = globalObject[Object.values(mainArr[i])[0]]
    }
}

console.log(myGlobalArr)

HELP WOULD BE APPRECIATED!!帮助将不胜感激!

#EDITED: #编辑:

It is going to be block of 3 .它将是3块。

You can do this using Array.reduce() .您可以使用Array.reduce() 来做到这一点。 On every iteration of reduce you can check to what index of the final array put your data using the current index of the object modulus 3 ( idx % 3 ):reduce每次迭代中,您可以使用对象modulus 3 ( idx % 3 ) 的当前索引检查最终数组的哪个索引放置您的数据:

 const input = [ {"animal": "cat"}, {"animal": "dog"}, {"animal": "elephant"}, {"vehicle": "car"}, {"vehicle": "bike"}, {"vehicle": "truck"}, {"toys": "a1"}, {"toys": "a2"}, {"toys": "a3"} ]; let res = input.reduce((acc, curr, idx) => { let [[k, v]] = Object.entries(curr); acc[idx % 3] = acc[idx % 3] || {}; acc[idx % 3][k] = v; return acc; }, []) console.log(res);
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}

You could take a hash table which takes care of the right index of the same key for the result set.您可以使用一个哈希表来处理结果集相同键的正确索引。

This works for an arbitrary count of objects/properties and order, as long as the same properties are in order.这适用于任意数量的对象/属性和顺序,只要相同的属性是有序的。

 var data = [ { animal: "cat" }, { animal: "dog" }, { animal: "elephant" }, { vehicle: "car" }, { vehicle: "bike" }, { vehicle: "truck" }, { toys: "a1" }, { toys: "a2" }, { toys: "a3" }], indices = {}, result = data.reduce((r, o) => { var key = Object.keys(o)[0]; indices[key] = indices[key] || 0; Object.assign(r[indices[key]] = r[indices[key]] || {}, o); indices[key]++; return r; }, []); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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

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