Search code examples
javascriptjquerylodashlinq.js

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


I have 2 arrays. users and posts. posts contain a property "post_by" which is the id of one of the users. I need to match the user and push the first & last name into the post object as a new property. Goal is I need to display the name of the user that made the post in a table.

note* I can use javascript, jquery, linq.js or lodash.

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

Solution

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