cusejuice
cusejuice

Reputation: 10681

Use underscore to replace object key from another object

Using underscore, how can I replace each data.type key with its corresponding object from example.

For example, I have:

  var example = [
    {
      id: 1,
      data: {
        type: '/api/data/1/'
      }
    },
    {
      id: 2,
      data: {
        type: '/api/data/2/'
      }
    },
  ];

And this:

  var data = [
    {
      id: 1,
      uri: '/api/data/1/'
    },
    {
      id: 2,
      uri: '/api/data/2/'
    }
  ];

Would like to produce:

  var example = [
    {
      id: 1,
      data: {
        type: {
          id: 1,
          uri: '/api/data/1/'
        }
      }
    },
    {
      id: 2,
      data: {
        type: {
          id: 2,
          uri: '/api/data/2/'
        }
      }
    },
  ];

Upvotes: 2

Views: 322

Answers (2)

RobG
RobG

Reputation: 147363

Libraries like underscore have largely been replaced by features in newer versions of ECMAScript. If you want to modify the original array (per Sushanth's answer), use ES5's forEach:

example.forEach(function(v, i) {
  example[i].data.type = data[i];
});

console.log(JSON.stringify(example));

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

You can just use a for loop if the items are sequential.

for(var i=0;i< example.length; i++) {
    example[i].data.type = data[i];
}

console.log(example);

Upvotes: 1

Related Questions