1

I am looking to change the structure of some data. Below is a sample of the data I am receiving

{
  ID1: {
         firstName: 'John',
         lastName: 'Doe'
      },
  ID2: {
         firstName: 'Jane',
         lastName: 'Doe'
      }
}

What I need to do is convert this into an array with the following format:

[
  { ID: ID1, firstName: 'John', lastName: 'Doe' },
  { ID: ID2, firstName: 'Jane', lastName: 'Doe' }
]

I prefer to use lodash if possible

3
  • I should have clarified.. The IDs are different for each entry. I updated the questions. Commented Jun 3, 2016 at 17:19
  • 1
    What specifically are you having problems with? How to iterate over an object? How to add a new element to an array? How to add a property to an object? Divide your problem into smaller problems and find solutions for them. All of these smaller problems have been asked before (or are covered in tutorials). Commented Jun 3, 2016 at 17:45
  • Also this has nothing to do with JSON. Commented Jun 3, 2016 at 17:46

3 Answers 3

5

Use Object.keys() and Array#map(). Object.keys() which helps to get all the properties of the object as an array. Then Array#map() can be used to iterate over the element and generate new array based on the returned element.

var data = {
  ID1: {
    firstName: 'John',
    lastName: 'Doe'
  },
  ID2: {
    firstName: 'Jane',
    lastName: 'Doe'
  }
};

var res = Object.keys(data) // get all object properties as an array
  .map(function(k) { // iterate and generate new array with custom element
    return { // generate custom array object based on the property and object and return
      ID: k, // k is property of ov=bjeck
      firstName: data[k].firstName, // get inner properties from data object using k
      larstName: data[k].lastName
    };
  })

console.log(res);


UPDATE : I've created new object instead of updating original object and returned it. If updating original object is not a problem then add additional property to object and return the reference inside the Array#map() callback function. This works if there is any number of inner properties but it updates original object.

var data = {
  ID1: {
    firstName: 'John',
    lastName: 'Doe'
  },
  ID2: {
    firstName: 'Jane',
    lastName: 'Doe'
  }
};

var res = Object.keys(data) // get all object properties as an array
  .map(function(k) { // iterate and generate new array with custom element
    data[k].ID = k; // add additional property
    return data[k]; // return the reference
  })

console.log(res);


Or in case you want to maintain the object and there is lots of inner object properties then do something like.

var data = {
  ID1: {
    firstName: 'John',
    lastName: 'Doe'
  },
  ID2: {
    firstName: 'Jane',
    lastName: 'Doe'
  }
};

var res = Object.keys(data) // get all object properties as an array
  .map(function(k) { // iterate and generate new array with custom element
    var obj = { // create an object to return
      ID: k
    };
    for (var key in data[k]) // iterate over object property
      if (data[k].hasOwnProperty(key)) // check the object has the property 
        obj[key] = data[k][key]; // add property to the newly generated object
    return obj; // return the object
  })

console.log(res);

Sign up to request clarification or add additional context in comments.

4 Comments

That's exactly what I was looking for. Could you please explain how it works? I am bit confused as where the value of 'k' comes from.
@SohrabHejazi But you'd prefer to use lodash. I made it in lodash
@SohrabHejazi I understand, but are you sure my solution returns an object?
@SohrabHejazi : updated, and Object.keys() return an array which contains all the object properties and first argument in map() method is current element which is the key in array.... , developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
2

Can you add ID to the objects? If so, then it can be achieved easy with:

var arr = _.values(obj);

Explanation:

Often developers duplicate key inside value to avoid many problems. They do like this:

{
  ID1: {
         ID: ID1,
         firstName: 'John',
         lastName: 'Doe'
      },
  ID2: {
         ID: ID2
         firstName: 'Jane',
         lastName: 'Doe'
      }
}

And then use only one command above and it returns only values of the object and make an array.

If it is not suites for you, then you need to add IDs manually like that:

var arr = _.map(obj, function(value, key) {
  value[ID] = key;
  return value;
});

Be careful, the code will change the original object, but in most of cases it is not a problem, but if you need to avoid this, you need:

var arr = _(obj)
  .clone()
  .map(obj, function(value, key) {
    value[ID] = key;
    return value;
  })
  .value();

2 Comments

What do you mean by adding ID to the objects?
@SohrabHejazi Both my solutions return array.
0

You can make use of map() to convert the object into an array and then use assign() to append the ID key value, this also makes sure that the original object does not get mutated.

Here is the ES6 version:

var result = _.map(data, (item, ID) => _.assign({ ID }, item));

var data = {
  ID1: {
         firstName: 'John',
         lastName: 'Doe'
      },
  ID2: {
         firstName: 'Jane',
         lastName: 'Doe'
      }
};

var result = _.map(data, (item, ID) => _.assign({ ID }, item));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>

Here's the es5 version:

var result = _.map(data, function(item, ID) { 
  return _.assign({ ID: ID }, item);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.