如何从元素数组 return 到新数组?
How to return to new array from Array of elements?
我有一个元素数组,我想用一个键作为名称映射到一个新的对象数组。
let array = ["abc", "def", "xyx"]
预期输出
let array1 = [{name: "abc"}, {name: "def"}, {name: "xyz"}]
您可以使用 array.map
:
let newArray = array1.map((value) => ({name: value});
let arr = ['a', 'b', 'c'];
let newArr = arr.map(el => ({ name: el }));
console.log(newArr);
你可以使用 map() 函数,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
let array = ["abc", "def", "xyx"]
const array1 = array.map( data => {
return {name:data}
})
/* this code will also work,if you dint specify the properties name
by default it will be the variable's name. In this case 'name' */
const array2 = array.map( name => {
return {name}
})
console.log(array1)
console.log(array2)
我有一个元素数组,我想用一个键作为名称映射到一个新的对象数组。
let array = ["abc", "def", "xyx"]
预期输出
let array1 = [{name: "abc"}, {name: "def"}, {name: "xyz"}]
您可以使用 array.map
:
let newArray = array1.map((value) => ({name: value});
let arr = ['a', 'b', 'c'];
let newArr = arr.map(el => ({ name: el }));
console.log(newArr);
你可以使用 map() 函数,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
let array = ["abc", "def", "xyx"]
const array1 = array.map( data => {
return {name:data}
})
/* this code will also work,if you dint specify the properties name
by default it will be the variable's name. In this case 'name' */
const array2 = array.map( name => {
return {name}
})
console.log(array1)
console.log(array2)