admin管理员组文章数量:1418438
I have an object like :
var obj1 = [{ first : 1, second : 2 },
{third : 3, fourth : 4},
{fifth : 5, sixth : 6}];
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];
I tried this :
var labels = [];
var values = [];
for(var key in obj1[0]){
labels.push(key);
values.push(obj1[0][key]);
}
But it results in
labels = ["first","second"];
values = [1,2];
I know this happens because I am iterating only the 0
index position. Can anyone suggest me a way to achieve the expected output.
I have an object like :
var obj1 = [{ first : 1, second : 2 },
{third : 3, fourth : 4},
{fifth : 5, sixth : 6}];
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];
I tried this :
var labels = [];
var values = [];
for(var key in obj1[0]){
labels.push(key);
values.push(obj1[0][key]);
}
But it results in
labels = ["first","second"];
values = [1,2];
I know this happens because I am iterating only the 0
index position. Can anyone suggest me a way to achieve the expected output.
- is jquery possible to use? – Daniel Gasser Commented May 10, 2015 at 5:18
- @pc-shooter I was thinking a pure javascript solution. But if jquery gives a better solution thens its fine to use jQuery – Zee Commented May 10, 2015 at 5:20
2 Answers
Reset to default 4Try like this
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);
for (var i = 0; i < obj1.length; i++) {
for (var key in obj1[i]) {
labels.push(key);
values.push(obj1[i][key]);
}
}
本文标签: javascriptSeparate keys and values from objectStack Overflow
版权声明:本文标题:javascript - Separate keys and values from object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745267713a2650702.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论