簡體   English   中英

比較2個對象數組。 按 id 匹配,將對象屬性推入數組

[英]compare 2 array of objects. match by ids, push object property into array

我有 2 個數組。 用戶和帖子。 帖子包含一個屬性“post_by”,它是其中一個用戶的 ID。 我需要匹配用戶並將名字和姓氏作為新屬性推送到帖子對象中。 目標是我需要在表格中顯示發布帖子的用戶的姓名。

注意* 我可以使用 javascript、jquery、linq.js 或 lodash。

撥弄 json小提琴

var users = [
    {
        "id": "15e640c1-a481-4997-96a7-be2d7b3fcabb",
        "first_name": "Kul",
        "last_name": "Srivastva",
    },
    {
        "id": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd",
        "first_name": "Rudy",
        "last_name": "Sanchez",
    },
    {
        "id": "636f9c2a-9e19-44e2-be88-9dc71d705322",
        "first_name": "Todd",
        "last_name": "Brothers"
    },
    {
        "id": "79823c6d-de52-4464-aa7e-a15949fb25fb",
        "first_name": "Mike",
        "last_name": "Piehota"
    },
    {
        "id": "e2ecd88e-c616-499c-8087-f7315c9bf470",
        "first_name": "Nick",
        "last_name": "Broadhurst"
    }
    ]

    var posts = [
    {
        "id": 1,
        "status": "Active",
        "post_title": "test title",
        "post_body": "test body",
        "post_by": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd"
    },
    {
        "id": 2,
        "status": "Fixed",
        "post_title": "test title two",
        "post_body": "test body two",
        "post_by": "79823c6d-de52-4464-aa7e-a15949fb25fb"
    }
]

https://jsfiddle.net/zy5oe25n/7/

console.log($.map(posts, function(post){
  var user = $.grep(users, function(user){
    return user.id === post.post_by;
  })[0];

  post.first_name = user.first_name;
  post.last_name = user.last_name;
  return post;
}));

這是一個 lodash 方法:

_.map(posts, function(item) {
    return _.assign(
        _.pick(_.find(users, { id: item.post_by }),
            'first_name', 'last_name'),
        item
    );
});

它使用map()將 posts 數組映射到新對象(不可變數據)的新數組。 然后使用find()定位用戶對象,並使用pick()獲取我們需要的屬性。 最后, assign()將 post 屬性添加到pick()創建的新對象中。

為了更好的衡量,使用 linq.js。

var userMap = Enumerable.From(users).ToObject("$.id");
posts.forEach(function (post) {
    var user = userMap[post.post_by];
    if (user) {
        post.first_name = user.first_name;
        post.last_name = user.last_name;
    }
});

請注意,我們對數組使用內置的forEach() ,該部分不需要 linq.js。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM