2017-10-21 71 views
-1

我有兩個數組:合併2 JavaScript數組

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

我有點失去了對這個。非常感謝任何人的幫助。

感謝

+0

請嘗試使用陣列功能試驗樣https://www.w3schools.com/jsref/ jsref_concat_array.asp –

回答

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

你可以使用一個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; }

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