Convert array of strings into an array of objects

前端 未结 5 1041
甜味超标
甜味超标 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);

提交回复
热议问题