繁体   English   中英

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

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

我在下面有这个json

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

我预期的 json 响应是:

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

我尝试了以下程序,但没有给我预期的输出,我想制作一个可以比较的数组并相应地添加:

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)

帮助将不胜感激!

#编辑:

它将是3块。

您可以使用Array.reduce() 来做到这一点。 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;}

您可以使用一个哈希表来处理结果集相同键的正确索引。

这适用于任意数量的对象/属性和顺序,只要相同的属性是有序的。

 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