Ad33 Ad33 - 5 months ago 8
Javascript Question

How to create an array of objects having values as objects from an array that has been created in javascript?

I have an array whose elements are in string format, like this:

somearray = [object, object, object]


where each object has a

fname: "abc", lname: "pqr", age: 31


I am trying to create an object from this array whose variable I have declared as var newobject = {}. I tried this:

newobject = somearray.map(function(x) {
return {
fname: x.fname,
lname: x.lname,
age: x.age
};
});


This does create an object of the format [object, object, object] where each object is

fname: "abc", lname: "pqr", age: 31


What I desire to achieve is 'fname' and 'lname' should be objects as in the following

fname: object, lname: object, age: 31


What are the modifications I will need to make? Where the fname and lname objects will be:

fname: {firstname: "abc"}


And I am doing this because in later part of the program I will be adding more properties to fname and lname.

Answer

Change your map function like

  var newobject = somearray.map(function(x) {
      return {
          fname: {
              fname: x.fname
          },
          lname: {
              lname: x.lname
          },
          age: x.age
      };
  });