如何根据一些Id将值插入到对象中

时间:2017-02-01 14:47:32

标签: javascript

我想根据该对象内的id将值插入到对象中。

第一个对象:

{
    "topics": [{
        "id": 131,
        "topicId": "1485853106269",
        "title": "Topic Title",
        "details": "topic details",
        "username": "ki****@gmail.com",
        "userImage": "assets/img/spiritual-icon4.png",
        "dayPosted": "1/31/2017, 5:16:53 PM"
    }, {
        "id": 132,
        "topicId": "1485863413654",
        "title": "Check",
        "details": "topic details",
        "username": "ki****@gmail.com",
        "userImage": "assets/img/spiritual-icon4.png",
        "dayPosted": "1/31/2017, 5:20:13 PM"
    }, {
        "id": 133,
        "topicId": "1485945328280",
        "title": "New Topic",
        "details": "Sample Topic",
        "username": "ki****@gmail.com",
        "userImage": "assets/img/spiritual-icon4.png",
        "dayPosted": "2/1/2017, 4:05:28 PM"
    }, {
        "id": 134,
        "topicId": "1485945483238",
        "title": "New Topic2",
        "details": "New Topic2",
        "username": "ki****@gmail.com",
        "userImage": "assets/img/spiritual-icon4.png",
        "dayPosted": "2/1/2017, 4:08:03 PM"
    }],
    "role": "ROLE_ADMIN"
}

第二个对象:

{
   "1485594764668": 1,
   "1485853106269": 2,
   "1485945483238": 1
}

我想根据匹配的属性"topicId": "1485853106269"将第二个对象的值插入第一个对象。

例如:第一个对象中"topicId": "1485853106269"的值与第二个对象内的键匹配,因此结果如下所示,附加值"count": 2

{
    "id": 131,
    "topicId": "1485853106269",
    "title": "Topic Title",
    "details": "topic details",
    "username": "ki****@gmail.com",
    "userImage": "assets/img/spiritual-icon4.png",
    "dayPosted": "1/31/2017, 5:16:53 PM",
    "count": 2 //ADDED here
}

2 个答案:

答案 0 :(得分:2)

一个简单的每个循环都可以:

obj.topics.forEach(item => item.count = counts[item.topicId])

答案 1 :(得分:2)



var obj = {"topics":[{"id":131,"topicId":"1485853106269","title":"Topic Title","details":"topic details","username":"ki****@gmail.com","userImage":"assets/img/spiritual-icon4.png","dayPosted":"1/31/2017, 5:16:53 PM"},{"id":132,"topicId":"1485863413654","title":"Check","details":"topic details","username":"ki****@gmail.com","userImage":"assets/img/spiritual-icon4.png","dayPosted":"1/31/2017, 5:20:13 PM"},{"id":133,"topicId":"1485945328280","title":"New Topic","details":"Sample Topic","username":"ki****@gmail.com","userImage":"assets/img/spiritual-icon4.png","dayPosted":"2/1/2017, 4:05:28 PM"},{"id":134,"topicId":"1485945483238","title":"New Topic2","details":"New Topic2","username":"ki****@gmail.com","userImage":"assets/img/spiritual-icon4.png","dayPosted":"2/1/2017, 4:08:03 PM"}],"role":"ROLE_ADMIN"};

var countObj = {
    "1485594764668": 1,
    "1485853106269": 2,
    "1485945483238": 1
};

obj.topics.forEach(function(o){
     var c = countObj[o.topicId];
     if(c !== undefined)
         o.count = c;
});

console.log(obj);