2

I have an array of string which I want to turn it to array of object.

array = ['a', 'b', 'c'];

I want to generate

array= [
  {'name': 'a', 'isChecked': false, 'availibility': 0 },
  {'name': 'b', 'isChecked': false, 'availibility': 0 },
  {'name': 'b', 'isChecked': false, 'availibility': 0 }
];

I tried below and still returning the originalArray!

array.map((name) => ({
  name,
  isChecked: false,
  availability: 0
}));

How would you do this?

1
  • 6
    map does not mutate the original array but returns a new one. Commented Aug 14, 2017 at 23:29

4 Answers 4

6

You can use map like this:

array= ['a', 'b', 'c'];
let newArr = array.map(item => {
  return {
    'name': item,
    'isChecked': false,
    'availibility': 0
  }
})

console.log(newArr);

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

Comments

2

You'll need to use the following, because as @ASDFGerte pointed out, map does not modify the original object, but returns a new one which you should assign to a variable. In this case, I've just assigned it back to the original array variable.

var array = ['a', 'b', 'c'];

array = array.map((name) => ({
    name,
    isChecked: false,
    availability: 0
}));

console.log(array);

Comments

2

Your map() works as expected, but it does return a new array. If you want to mutate the original array, use forEach()

array.forEach((val, i) => array[i] = {
    name: val,
    isChecked: false,
    availability: 0
})

Comments

1

Old-fashioned way:

var outputArray = [];
var inputArray = ['a', 'b', 'c'];
for (var i=0, len = inputArray.length; i < len; i++) {
    outputArray.push({
           name : inputArray[i],
           isChecked : false,
           availability : 0
    });
}

If you want to use map() you need to store the object in new array.

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.