admin管理员组

文章数量:1296889

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
}]

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
}]
Share Improve this question edited May 14, 2016 at 9:32 0xdw 3,8422 gold badges27 silver badges43 bronze badges asked May 14, 2016 at 7:46 Satwinder SinghSatwinder Singh 6271 gold badge7 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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.

本文标签: javascriptHow to remove key from Array of ObjectStack Overflow