Convert array of strings into an array of objects

前端 未结 5 1039
甜味超标
甜味超标 2020-11-30 14:40

I have this JavaScript array:

[ \"124857202\", \"500255104\", \"78573M104\" ]

I want to convert this particular array into an array of obje

相关标签:
5条回答
  • 2020-11-30 15:01

    I want to convert this particular array into an array of objects as shown below

    If you want to change the actual array in place (rather than creating a new array), you can use a for loop to iterate the indexes of your array. For each index, you can replace the value with an object {name: arr[i]}. This object has a name key, and takes a value which is the current element arr[i].

    const arr = [ "124857202", "500255104", "78573M104" ];
    for(let i = 0; i < arr.length; i++) {
      arr[i] = {name: arr[i]};
    }
    console.log(arr);

    0 讨论(0)
  • 2020-11-30 15:03

    Another approach - Array#reduce.

    var arr = ["124857202", "500255104", "78573M104"];
    var res = arr.reduce(function(s, a){
        s.push({name: a});
        return s;
      }, [])
      
    console.log(res);

    0 讨论(0)
  • 2020-11-30 15:04

    I would take a look at the array.map function in javascript.

    const mappedArr = arr.map(value => {
      return {
        name: value
      }
    })
    
    0 讨论(0)
  • 2020-11-30 15:22

    You can use

    var arrayOfStrings = ["124857202", "500255104", "78573M104"];
    var arrayOfObjects = [];
    
    arrayOfStrings.forEach(function (element, index) {
       arrayOfObjects.push({
            name: element,
       })
    });
    
    0 讨论(0)
  • 2020-11-30 15:23

    Use Array#map to convert each value into a different value:

    var newArr = arr.map(function(value) {
      return {name: value};
    });
    

    Array#map applies the callback to each element in the array and returns a new array containing the return values of the callback.

    0 讨论(0)
提交回复
热议问题