2

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/'
        }
      }
    },
  ];
1
  • is this a hw problem? Commented Aug 4, 2015 at 22:43

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.