4

I have Array objects like below , How to convert this format into Array of objects and remove key.

{
  "9417702107": {
    "name": "Sunny",
    "phone": "9417702107",
    "exists": true
  },
  "8826565107": {
    "name": "Gurwinder",
    "phone": "8826565107",
    "exists": true
  }
}

How to convert this into below format using javascript:

[{
  "name": "Sunny",
  "phone": "9417702107",
  "exists": true
}, {
  "name": "Gurwinder",
  "phone": "8826565107",
  "exists": true
}]

3 Answers 3

5

Use a simple loop:

array = [];
for (var key in obj) {
    array.push(obj[key]);
}

As in the other answer, there's no guarantee that the elements of the array will be in the same order as in the object.

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

Comments

1

simply try this

var output = Object.keys(obj).map(function(key){
  return obj[key];
})

Note that there is no guarantee that order of items in output array will be same as in the order key-values in your object as you see it.

if the order is important, then put an new attribute called order in the object itself

var obj {
"9417702107": 
 {
  "name": "Sunny",
  "phone": "9417702107",
  "exists": true,
  "order_sequence" : 1
},
"8826565107": {
  "name": "Gurwinder",
  "phone": "8826565107",
  "exists": true,
  "order_sequence" : 1
}
}

and then after converting to array, you can sort on the order_sequence

var output = Object.keys(obj).map(function(key){
  return obj[key];
}).sort( function(a,b){
   return a.order_sequence - b.order_sequence;
});

5 Comments

but be aware that there's no guarantee in which order the elements will appear in the resulting array
@Alnitak yes, that is true if this array is generated dynamically.
@gurvinder372 then what's alternative. vire.??
@SunnyDhiman with the object, order of key is immaterial and has no meaning since object is supposed to be key-value affair and not item based affair. If the order is important, then the object needs to have an order attribute.
@gurvinder372 ok i got it. Thanks..!!
0

Use Object.keys and for-cycle.

var keys = Object.keys(input), output = [];
for (var i = 0, length = keys.length; i < length; ++i)
    ouptput.push(input[keys[i]]);
console.log(output);

Some tips:
- Cycles in this case gives move performance than map function, because in today JS engines: fewer functions calls, greater performance.
- For-each (for (var k in input) {}) is slower than Object.keys and cycle for/while.

This is acceptable for today implementation Google V8 and Mozilla SpiderMonkey.

1 Comment

there is any guarantee in order remain same..??

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.