简体   繁体   English

使用下划线从javascript中的对象列表中提取值

[英]Extract values from a list of objects in javascript using underscore

I have a list of objects, where each object has numerical values: 我有一个对象列表,其中每个对象都有数值:

var cpuInfo = [
  { user: 189625143,
    nice: 0,
    sys: 40239022,
    idle: 2087123838,
    irq: 720490 },
  { user: 76627160,
    nice: 0,
    sys: 35444113,
    idle: 2204916386,
    irq: 18233303 }
]

I need to calculate the value of idle divided by the sum of all values. 我需要计算idle值除以所有值的总和。

For that, I need to get the sum of all of the values in all of the objects. 为此,我需要获取所有对象中所有值的总和。

I've tried doing this to extract just the values: 我尝试这样做只是提取值:

_(cpuInfo).each(_.values)

I expected it to return a list like so: 我希望它返回这样的列表:

[189625143, 0, 40239022, 2087123838, 720490, 76627160, 0, 35444113, 2204916386, 18233303]

But for some reason it returns the exact same thing I started out with - a list of objects. 但是由于某种原因,它会返回与我刚开始时完全相同的东西-对象列表。 Even if I expand it to this: 即使我将其扩展为:

_(cpuInfo).each(function(item) { return _(item).values() })

It still returns just the list of objects. 它仍然仅返回对象列表。

What am I doing wrong? 我究竟做错了什么?

var res = _.map(cpuInfo, function (el) {
  return _.values(el)  
})
res = _.flatten(res)

console.log(res);

Demo: http://jsbin.com/rodipu/1/edit?js,console 演示: http : //jsbin.com/rodipu/1/edit?js,console

In pure JavaScript 用纯JavaScript

temp = [];
cpuInfo.forEach(function(obj){
    Object.keys(obj).forEach(function(k){
        temp.push(obj[k]);
    });
});

Ref - Object.keys() , Array.prototype.forEach() 引用Object.keys()Array.prototype.forEach()

Note - both functions compatible with >IE8 注意- 两种功能均与> IE8兼容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM