Convert array of string to array of object using es6 or lodash

a 夏天 提交于 2020-02-02 15:06:40

问题


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:


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



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



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/45684461/convert-array-of-string-to-array-of-object-using-es6-or-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!