【问题标题】:Compare two objects and extract the ones that have same Key in javascript比较两个对象并在 javascript 中提取具有相同 Key 的对象
【发布时间】:2018-03-29 07:45:19
【问题描述】:

我有以下两个对象

var productionTime= [
    {Rob3: 20},
    {Rob8: 100},
    {Rob4: 500},
    {Rob1: 100},
    {Rob5: 500}
];
var Busytime= [
    {Rob4: 10},
    {Rob3: 200},
    {Rob8: 100},
    {Rob5: 200},
    {Rob1: 100}
];

现在我想将“productionTime”中的每个项目除以具有相同键的相应“BusyTime”。 例如 productionTime.Rob3 应除以 BusyTime.Rob3,productionTime.Rob8 应除以 BusyTime.Rob8 等等。

如何在 javascript/nodejs 中使用 array.find() 或 array.filter() 做到这一点?

P.S:我知道我可以通过使用两个嵌套的 forEach 循环来做到这一点,但我猜这很慢

【问题讨论】:

  • 修复数据结构(例如var productionTime = { Rob3: 20, Rob8: 100, ... }),然后您的算法归结为一个for循环。
  • 数据结构无法更改,因为我可能必须为每个对象添加其他键。例如。 var productionTime = [ {Rob3: 20, hasTime="date or Time"}, {Rob8: 100, hasTime="date or Time"}, {Rob4: 500, hasTime="date or Time"}, {Rob1: 100 , hasTime="date or Time"}, {Rob5: 500, hasTime="date or Time"} ];

标签: javascript arrays node.js object javascript-objects


【解决方案1】:

您可以为每个数组使用一个哈希表和一个循环。

var productionTime = [{ Rob3: 20 }, { Rob8: 100 }, { Rob4: 500 }, { Rob1: 100 }, { Rob5: 500 }];
    busytime = [{ Rob4: 10 }, { Rob3: 200 }, { Rob8: 100 }, { Rob5: 200 }, { Rob1: 100 }],
    hash = Object.create(null);

busytime.forEach(function (o) {
    var key = Object.keys(o)[0];
    hash[key] = o[key];
});

productionTime.forEach(function (o) {
    var key = Object.keys(o)[0];
    o[key] /= hash[key];
});

console.log(productionTime);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 简洁优雅
【解决方案2】:

使用Object#assignspread syntax 将两个数组转换为对象。使用Object#keys 从其中一个获取密钥,并使用Array#map 迭代密钥。使用shorthand property names为每个键创建一个新对象:

const productionTime = [{"Rob3":20},{"Rob8":100},{"Rob4":500},{"Rob1":100},{"Rob5":500}];
const Busytime= [{"Rob4":10},{"Rob3":200},{"Rob8":100},{"Rob5":200},{"Rob1":100}];

// create objects from both arrays
const productionTimeObj = Object.assign({}, ...productionTime);
const busytimeObj = Object.assign({}, ...Busytime);

// get the keys from one of the objects, and iterate with map
const result = Object.keys(productionTimeObj).map((key) => ({ 
  // create a new object with the key, and the result of the division
  [key]: productionTimeObj[key] / busytimeObj[key]
}));

console.log(result);

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2016-09-15
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多