操纵对象值并生成新对象

时间:2016-06-11 18:43:04

标签: javascript

我有一个Object作为键ID和作为Value的对象数组,我需要从这个生成一个Object

数组

var bears = { 
 "1" :
    [ 
        { 'total_bears': 2, 'bear_id': 1, 'location': 'CA' },
        { 'bear_age': 100, 'bear_id': 1, 'location': 'CA' },
        { 'total_bears': 1, 'bear_id': 1, 'location': 'NM' },
        { 'bear_age': 10, 'bear_id': 1, 'location': 'NM' }
    ],
 "2" :
    [ 
        { 'total_bears': 1, 'bear_id': 2, 'location': 'CA' },
        { 'bear_age': 50, 'bear_id': 2, 'location': 'CA' } 
    ]
  };

结果

{ 'bear_id' : 1, 'locationCAtotal_bears' : 2, 'locationCAbear_age': 100, 'locationNMtotal_bears': 1, 'locationNMbear_age':  100}

{ 'bear_id' : 2, 'locationCAtotal_bears' : 1, 'locationCAbear_age': 50}

我有什么

for (var key in bears) {
  var arr = bears[key];
  var obj = {};
  var new_arr = arr.map(function(item) {
    if (item.location == 'CA') {
        obj.bear_id = item.bear_id;
        obj.locationCAtotal_bears = item.total_bears;
        obj.locationCAbear_age = item.bear_age;
    }
    else if (item.location == 'NM') {
        obj.bear_id = item.bear_id;
        obj.locationNMtotal_bears = item.total_bears;
        obj.locationNMbear_age = item.bear_age;
    }

    return obj
  });
}

这是我尝试的众多代码之一。我尝试了不同的东西,但仍然没有运气

2 个答案:

答案 0 :(得分:1)

使用 Array#forEach Array#reduce 方法

session_write_close()

答案 1 :(得分:0)

工作解决方案,在迭代地图时,对象(item.total_bears)值未定义,你检查if条件是这样的。

var bears = { 
 "1" :
    [ 
    { 'total_bears': 2, 'bear_id': 1, 'location': 'CA' },
    { 'bear_age': 100, 'bear_id': 1, 'location': 'CA' },
    { 'total_bears': 1, 'bear_id': 1, 'location': 'NM' },
    { 'bear_age': 10, 'bear_id': 1, 'location': 'NM' }
    ],
 "2" :
    [ 
    { 'total_bears': 1, 'bear_id': 2, 'location': 'CA' },
    { 'bear_age': 50, 'bear_id': 2, 'location': 'CA' } 
    ]
  };

var newBears = [];
for (var key in bears) {
  var arr = bears[key];
  var obj = {};
  var new_arr = arr.map(function(item) {

    if (item.location === 'CA') {
    obj.bear_id = item.bear_id;
    if (item.total_bears)
        obj.location_CAtotal_bears = item.total_bears;
    obj.locationCAbear_age = item.bear_age;
    }
    else if (item.location === 'NM') {
    obj.bear_id = item.bear_id;
    if (item.total_bears)
        obj.location_NMtotal_bears = item.total_bears;
    obj.locationNMbear_age = item.bear_age;
    }

    return obj
  });
  newBears.push(obj);
}
console.log(JSON.stringify(newBears));

现在newBears数组将有你的结果。