问题
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