【问题标题】:compare 2 array of objects. match by ids, push object property into array比较 2 个对象数组。按 ids 匹配,将对象属性推入数组
【发布时间】:2016-04-07 08:35:24
【问题描述】:

我有 2 个数组。用户和帖子。帖子包含一个属性“post_by”,它是其中一个用户的 ID。我需要匹配用户并将名字和姓氏作为新属性推送到 post 对象中。目标是我需要在表格中显示发布帖子的用户的姓名。

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

摆弄 json fiddle

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

【问题讨论】:

    标签: javascript jquery lodash linq.js


    【解决方案1】:

    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;
    }));
    

    【讨论】:

    • 对不起,应该更清楚。我需要将用户的名字和姓氏推送到帖子对象中
    • 哦,你想合并吗?
    • 你正在改变数据,你不应该使用map()each()会更合适。
    【解决方案2】:

    这是一个 lodash 方法:

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

    它使用map() 将帖子数组映射到新对象(不可变数据)的新数组。然后它使用find() 来定位用户对象,并使用pick() 来获取我们需要的属性。最后,assign() 将 post 属性添加到 pick() 创建的新对象中。

    【讨论】:

      【解决方案3】:

      为了更好的衡量,使用 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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多