我有一個元素陣列,我想映射到一個以鍵為名稱的新物件陣列。
let array = ["abc", "def", "xyx"]
預期產出
let array1 = [{name: "abc"}, {name: "def"}, {name: "xyz"}]
uj5u.com熱心網友回復:
您可以使用array.map:
let newArray = array1.map((value) => ({name: value});
uj5u.com熱心網友回復:
let arr = ['a', 'b', 'c'];
let newArr = arr.map(el => ({ name: el }));
console.log(newArr);
uj5u.com熱心網友回復:
你可以使用 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/378787.html
