我有这个数组:
myArray = ["AAA","BBB",...,"ZZZ"];
我想将其转换为对象数组。像这样:
myArray = [
{
"Id": "111",
"Value": "AAA"
},
....
{
"Id": "111",
"Value": "ZZZ"
},
];
我试图像这样使用 map 方法:
myArray.map(str => {
let obj = {};
obj['Id'] = '111';
obj['Value'] = str;
});
但是 console.log(myArray)
输出以下内容:
未定义
答案 0 :(得分:1)
您需要从mapper函数返回结果。
let myNewArray = myArray.map( str => {
let obj = {};
obj['Id'] = '111' ;
obj['Value'] = str ;
return obj;
});
// or
let myNewArray = myArray.map( str => ({Id:111,Value:str}) );
// parenthesis are needed to remove the ambiguity with `{}`
console.log(myNewArray);
答案 1 :(得分:1)
这是使用Array#map
const data = myArray = ["AAA","BBB","ZZZ"];
let result = data.map(e => ({'Id': '111', 'Value': e}));
console.log(result);
答案 2 :(得分:0)
您需要将结果返回到新变量或现有变量中,因为map
创建了一个新数组,并且不会更改您要遍历的变量。
const myArrayOfObjects = myArray.map( str => {
let obj = {};
obj['Id'] = '111' ;
obj['Value'] = str ;
return obj;
});