javascript - Separate keys and values from object - Stack Overflow

I have an object like :var obj1 = [{ first : 1, second : 2 },{third : 3, fourth : 4},{fifth : 5, sixth

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.

Share Improve this question edited Jun 7, 2017 at 4:34 adddff 271 silver badge8 bronze badges asked May 10, 2015 at 5:15 ZeeZee 8,4885 gold badges38 silver badges59 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 4

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745267713a4619557.html

相关推荐

  • javascript - Separate keys and values from object - Stack Overflow

    I have an object like :var obj1 = [{ first : 1, second : 2 },{third : 3, fourth : 4},{fifth : 5, sixth

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信