获取对象数组中的值,该值是另一个对象内的值

时间:2017-08-16 07:30:06

标签: javascript object

如果我有这样的东西

var response =[{2017-03-17:[{command:"00",date_time:"2017-03-17",device_id:"ITPL",e1:"2.30",e2:"3.30",e3:"4.40",voltage:"270"},{command:"00",date_time:"2017-03-17",device_id:"ITPL",e1:"2.30",e2:"3.30",e3:"4.40",voltage:"290"}]},
               {2017-04-17:[{command:"00",date_time:"2017-04-22",device_id:"ITPL",e1:"2.30",e2:"3.30",e3:"4.40",voltage:"240"},{command:"00"date_time:"2017-04-22",device_id:"ITPL",e1:"2.30",e2:"3.30",e3:"4.40",voltage:"250"}]}]

我希望将此内容转换为类似

的内容
[{x:2017-03-17, y:270},{x:2017-03-17, y:290},{x:2017-04-22, y:240},{x:2017-04-22,y:250}]

这是我尝试的,但它显示错误

    var tArray = [];
response.forEach(a=>{
    let newObj = {x:a.date_time,y:a.voltage}
    tArray.push(newObj);
})

1 个答案:

答案 0 :(得分:1)

您可以将内部值映射到数组中,并从外部对象获取键以获取新的结果数组。

var response = [{ "2017-03-17": [{ command: "00", date_time: "2017-03-17", device_id: "ITPL", e1: "2.30", e2: "3.30", e3: "4.40", voltage: "270" }, { command: "00", date_time: "2017-03-17", device_id: "ITPL", e1: "2.30", e2: "3.30", e3: "4.40", voltage: "290" }] }, { "2017-04-17": [{ command: "00", date_time: "2017-04-22", device_id: "ITPL", e1: "2.30", e2: "3.30", e3: "4.40", voltage: "240" }, { command: "00", date_time: "2017-04-22", device_id: "ITPL", e1: "2.30", e2: "3.30", e3: "4.40", voltage: "250" }] }],
    result = response.reduce(function (r, o) {
        var key = Object.keys(o)[0];
        return r.concat(o[key].map(function (p) {
            return { x: key, y: p.voltage };
        }));
    }, []);

console.log(result);