1

I have an array like this,

var items = ['1','2','3']

and i want the output as newItems = [{'id':1}.{'id':2},{'id':3}];

  newItems = [{'id':''}]
  for(var i = 0;i<items.length;i++){
           newItems[i].id = type[i];
  }

Can anyone please help me.Thanks.

0

3 Answers 3

5

You can use map method for this, which creates a new array and applies a provided callback function for every item in the array.

var items = ['1','2','3']
console.log(items.map(function(item){
  return {"id":item}
}));

Sign up to request clarification or add additional context in comments.

Comments

3

Use map:

newItems = items.map(function(item) { return {'id': parseInt(item) }; });

EDIT: I added parseInt() since the user's desired output included unquoted integers.

Comments

0

var items = ['1','2','3'];
var newItems = items.map(function(item) {
  var obj = {};
  obj.id = +item; // '+' if you wish to convert item from string to number
  return obj;
});

console.log(newItems); //[{'id':1},{'id':2},{'id':3}]

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.