首页 > 解决方案 > 如何在jQuery / javascript中将多个对象合并为一个对象

问题描述

我有一个对象数组如下:

var jsonResponse = [
{"Geo":"Asia",
"Country":["China","Japan","India"],
"contact": "x@y.com"},
{"Geo":"Europe",
"Country":["Austria","Germany","UK"],
"contact": "x@y.com"},
{"Geo":"Africa",
"Country":"Egypt",
"contact": "z@z.com"},
... ];

我想按键循环遍历每个对象,合并所有唯一值并存储在一个新的对象数组中。

结果应如下所示:

var newjsonResponse = [
{"Geo":"world wide",
"Country":["China","Japan","India","Austria","Germany","UK","Egypt"],
"contact": ["x@y.com","z@z.com"]
}];

这是我的代码。任何建议请我做错了什么?非常感谢。

var jsonResponse = [
{"Geo":"Asia",
"Country":["China","Japan","India"],
"contact": "x@y.com"},
{"Geo":"Europe",
"Country":["Austria","Germany","UK"],
"contact": "x@y.com"},
{"Geo":"Africa",
"Country":"Egypt",
"contact": "z@z.com"}];

var arrGeo = [];
var arrCountry = [];
var arrcontact = [];
var newjsonResponse = [{"Geo":"world wide"}];

$.each(jsonResponse, function(key,value) {
arrCountry.push(value["Country"]);
arrcontact.push(value["contact"]);
newjsonResponse["Country"].push(arrCountry);
newjsonResponse["Contact"].push(arrcontact);
});
console.log(newjsonResponse);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

标签: javascriptjqueryarraysjson

解决方案


没有 jquery,但应该几乎相同,因为您只是使用 jquery 进行循环。

const jsonResponse = [
  { Geo: "Asia", Country: ["China", "Japan", "India"], contact: "x@y.com" },
  { Geo: "Europe", Country: ["Austria", "Germany", "UK"], contact: "x@y.com" },
  { Geo: "Africa", Country: "Egypt", contact: "z@z.com" },
];

const arrGeo = [];
const arrCountry = [];
const arrcontact = [];

for (const data of jsonResponse) {
  if (typeof data.Country === "string") {
    arrCountry.push(data.Country);
  } else {
    arrCountry.push(...data.Country);
  }

  if (!arrcontact.includes(data.contact)) {
    arrcontact.push(data.contact);
  }
}

const newjsonResponse = [
  {
    Geo: "world wide",
    Country: arrCountry,
    contact: arrcontact,
  },
];

console.log(newjsonResponse);

另一种方式:

const jsonResponse = [
  { Geo: "Asia", Country: ["China", "Japan", "India"], contact: "x@y.com" },
  { Geo: "Europe", Country: ["Austria", "Germany", "UK"], contact: "x@y.com" },
  { Geo: "Africa", Country: "Egypt", contact: "z@z.com" },
];

const newjsonResponse = { Geo: "world wide", Country: [], contact: [] };

for (const item of jsonResponse) {
  // Convert single country into a array for simplicity
  const countries =
    typeof item.Country === "string" ? [item.Country] : item.Country;

  // Loop over every country, checking that we don't add a duplicate
  for (const country of countries) {
    if (!newjsonResponse.Country.includes(country)) {
      newjsonResponse.Country.push(country);
    }
  }

  // Add contact if not allready in list
  if (!newjsonResponse.contact.includes(item.contact)) {
    newjsonResponse.contact.push(item.contact);
  }
}

console.log(newjsonResponse);


推荐阅读