如何在JavaScript中将字符串数组转换为对象数组?

时间:2018-10-05 09:50:16

标签: javascript arrays data-conversion

我有这个数组:

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)输出以下内容:

  

未定义

3 个答案:

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Using_map_to_reformat_objects_in_an_array

答案 1 :(得分:1)

这是使用Array#map

的干净ES6一线版

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