-3

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.

d33a
  • 690
  • 1
  • 14
  • 39

1 Answers1

0

Change your map function like

  var newobject = somearray.map(function(x) {
      return {
          fname: {
              fname: x.fname
          },
          lname: {
              lname: x.lname
          },
          age: x.age
      };
  });
Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70
  • 1
    @Ad33 May I ask what the reason for this requirement is? Why would you nest an object property in an object as the property of the same name? In other words: you’d need to access the value as `somearray[`…`].fname.fname` as opposed to as simply `somearray[`…`].fname` — why do you want this? – Sebastian Simon Jun 20 '16 at 04:15
  • @Xufox I have mentioned the same name here, although its not. And in the late part of the program I add more properties to this object. That's why I needed it this way. Thanks though :) – d33a Jun 20 '16 at 06:24