在数组json

时间:2019-03-08 04:47:02

标签: javascript arrays json loops

我下面有这个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)

将获得帮助!

#EDITED:

它将是3的块。

2 个答案:

答案 0 :(得分:1)

您可以使用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;}

答案 1 :(得分: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; }