admin管理员组

文章数量:1334174

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?

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?

Share Improve this question edited Aug 14, 2017 at 23:37 P.S. 16.4k14 gold badges65 silver badges86 bronze badges asked Aug 14, 2017 at 23:26 Negin BasiriNegin Basiri 1,3754 gold badges26 silver badges49 bronze badges 1
  • 6 map does not mutate the original array but returns a new one. – ASDFGerte Commented Aug 14, 2017 at 23:29
Add a ment  | 

4 Answers 4

Reset to default 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);

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

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

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.

本文标签: javascriptConvert array of string to array of object using es6 or lodashStack Overflow