【问题标题】:Converting multiple same key object in single object within array json在数组json中的单个对象中转换多个相同的键对象
【发布时间】:2025-11-26 00:25:01
【问题描述】:

我在下面有这个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的块。

【问题讨论】:

  • 链接元素的规则是什么?总是 3 块吗?
  • 是的!... 永远是 3。

标签: javascript arrays json loops


【解决方案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;}

【讨论】:

    【解决方案2】:

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

    这适用于任意数量的对象/属性和顺序,只要相同的属性按顺序排列即可。

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

    【讨论】: