Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of strings into an array of objects

I have this JavaScript array:

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

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

[
  { name: "124857202" },
  { name: "500255104" },
  { name: "78573M104" }
]
like image 274
Rihana Avatar asked Mar 08 '17 21:03

Rihana


People also ask

How do you convert an array into an array of objects?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.

Can you convert a string to an array?

We can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array.


4 Answers

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);
like image 32
kind user Avatar answered Oct 08 '22 18:10

kind user


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

Or, if you want to make a new array and leave the original untouched, you can use Felix's answer, here it can be re-written to use more modern ES6 features to make it more concise, such as an arrow function and shorthand property names:

const arr = [ "124857202", "500255104", "78573M104" ];
const res = arr.map(name => ({name}));
console.log(res);
like image 25
Nick Parsons Avatar answered Oct 08 '22 18:10

Nick Parsons


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.

like image 54
Felix Kling Avatar answered Oct 08 '22 18:10

Felix Kling


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

const mappedArr = arr.map(value => {
  return {
    name: value
  }
})
like image 33
gehsekky Avatar answered Oct 08 '22 18:10

gehsekky