合并2个javascript数组

时间:2017-10-21 19:37:44

标签: javascript arrays json

我有两个数组:

const calendar = [
    {"_id":"Jan"}, {"_id":"Feb"}, {"_id":"Mar"},
    {"_id":"Apr"}, {"_id":"May"}, {"_id":"Jun"},
    {"_id":"Jul"}, {"_id":"Aug"}, {"_id":"Sep"},
    {"_id":"Oct"}, {"_id":"Nov"}, {"_id":"Dec"}
]

const count = [
    {"_id":"Jan","count":1}, {"_id":"Apr","count":6},
    {"_id":"May","count":5}, {"_id":"Feb","count":1},
    {"_id":"Jul","count":1}, {"_id":"Mar","count":2},
    {"_id":"Jun","count":2}
]

我想合并两个数组,这样当那个月没有计数时,请将其设为"count":0

例如,新数组应如下所示:

const final = [
    {"_id":"Jan","count":1}, {"_id":"Feb","count":1},
    {"_id":"Mar","count":2}, {"_id":"Apr","count":6},
    {"_id":"May","count":5}, {"_id":"Jun","count":2},
    {"_id":"Jul","count":1}, {"_id":"Aug","count":0},
    {"_id":"Sep","count":0}, {"_id":"Oct","count":0},
    {"_id":"Nov","count":0}, {"_id":"Dec","count":0}
]

我对此有点失落。非常感谢任何人的帮助。

由于

3 个答案:

答案 0 :(得分:2)

首先为计数创建ID的映射。然后将所有日历月映射到创建的映射中的计数,如果不存在,则默认为0.

var countMap = {};
count.forEach((a) => {
    countMap[a._id] = a.count
});

const final = calendar.map((month) => ({_id: month._id, count: countMap[month._id] ||0}))

你可以在这里看到一个有效的例子:https://jsfiddle.net/z4sdcuku/

答案 1 :(得分:1)

您可以使用Map并首先获取所有计数。然后映射新对象。



var calendar = [{ _id: "Jan" }, { _id: "Feb" }, { _id: "Mar" }, { _id: "Apr" }, { _id: "May" }, { _id: "Jun" }, { _id: "Jul" }, { _id: "Aug" }, { _id: "Sep" }, { _id: "Oct" }, { _id: "Nov" }, { _id: "Dec" }],
    count = [{ _id: "Jan", count: 1 }, { _id: "Apr", count: 6 }, { _id: "May", count: 5 }, { _id: "Feb", count: 1 }, { _id: "Jul", count: 1 }, { _id: "Mar", count: 2 }, { _id: "Jun", count: 2 }],
    map = new Map(count.map(o => [o._id, o.count])),
    final = calendar.map(o => Object.assign({}, o, { count: map.get(o._id) || 0 }));

console.log(final);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:0)

这将为你做到:

const calendar = [{
  "_id": "Jan"
}, {
  "_id": "Feb"
}, {
  "_id": "Mar"
}, {
  "_id": "Apr"
}, {
  "_id": "May"
}, {
  "_id": "Jun"
}, {
  "_id": "Jul"
}, {
  "_id": "Aug"
}, {
  "_id": "Sep"
}, {
  "_id": "Oct"
}, {
  "_id": "Nov"
}, {
  "_id": "Dec"
}];

const count = [{
  "_id": "Jan",
  "count": 1
}, {
  "_id": "Apr",
  "count": 6
}, {
  "_id": "May",
  "count": 5
}, {
  "_id": "Feb",
  "count": 1
}, {
  "_id": "Jul",
  "count": 1
}, {
  "_id": "Mar",
  "count": 2
}, {
  "_id": "Jun",
  "count": 2
}]

var result = [];
for (var mth = 0; mth < calendar.length; mth++) {
  var ct = 0;
  for (var mthCt = 0; mthCt < count.length; mthCt++) {
    if (calendar[mth]._id === count[mthCt]._id) {
      ct = count[mthCt].count;
    }
  }
  result[mth] = {
    "id": calendar[mth]._id,
    "count": ct
  }
}
document.getElementById('output').textContent = JSON.stringify(result);

JSFiddle