将键和值与对象分开 [英] Separate keys and values from object
本文介绍了将键和值与对象分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的对象:
I have an object like :
var obj1 = [{ first : 1, second : 2 },
{third : 3, fourth : 4},
{fifth : 5, sixth : 6}];
我想将键
和 values
分成2个不同的 arrays
,这样结果应该是
I want to separate the keys
and values
into 2 different arrays
such that the result should be
var labels = [first, second, third, fourth, fifth, sixth];
var values = [1,2,3,4,5,6];
我尝试过这个:
var labels = [];
var values = [];
for(var key in obj1[0]){
labels.push(key);
values.push(obj1[0][key]);
}
但是会导致
labels = ["first","second"];
values = [1,2];
我知道发生这种情况是因为我只迭代了 0
索引位置.谁能建议我实现预期输出的方法.
I know this happens because I am iterating only the 0
index position. Can anyone suggest me a way to achieve the expected output.
推荐答案
尝试这样
var obj1 = [{ first : 1, second : 2 },
{third : 3, fourth : 4},
{fifth : 5, sixth : 6}];
var key=[];
var value=[];
obj1.forEach(function(item){
for(i in item)
{
key.push(i);
value.push(item[i]);
}
});
console.log(key);
console.log(value);
这篇关于将键和值与对象分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文