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
3 Answers
Reset to default 5Use 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
版权声明:本文标题:javascript - How to remove key from Array of Object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741636067a2389646.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论