gpt4 book ai didi

Javascript 玩对象项

转载 作者:行者123 更新时间:2023-11-30 16:06:49 25 4
gpt4 key购买 nike

我有 2 组对象,例如:

var objA = {};
objA.data1a = 100;
objA.data2a = 70;
objA.data3a = 16;
objA.data4a = 37;
objA.data5a = 88;
//my ObjA will contain the following
//{"data1a":100, "data2a":70, ......... "data5a":88}

var objB = {}
objA.data1b = 19;
objA.data2b = 5;
objA.data3b = 7;
objA.data4b = 6;
objA.data5b = 2;

var getDifferences = {};

//I want to get the differences using a loop but I'm not sure how am I able to do so.
//I am able to do this currently
// getDifferences.data1 = objA.data1a - objB.data1b;
// getDifferences.data2 = objA.data2a - objB.data2b;
// getDifferences.data3 = objA.data3a - objB.data3b;

我可以知道是否有一个循环遍历一个对象,以便对于每个循环我都可以减去差异并将差异存储到另一个对象中?

最佳答案

键的迭代。我假设 objB 应该包含其他值。

var objA = { data1a: 100, data2a: 70, data3a: 16, data4a: 37, data5a: 88 },
objB = { data1b: 19, data2b: 5, data3b: 7, data4b: 6, data5b: 2 },
getDifferences = {};

Object.keys(objA).forEach(function (k) {
var kk = k.substring(0, k.length - 1);
getDifferences[kk] = objA[kk + 'a'] - objB[kk + 'b'];
});

document.write('<pre>' + JSON.stringify(getDifferences, 0, 4) + '</pre>');

更多例子

What if.. my naming were different? EXAMPLE: var storeA = {}; {"1000": 532, "2020": 123} and var storeB = {}; {"1000": 200, "2020": 12}

var storeA = {"1000": 532, "2020": 123},
storeB = {"1000": 200, "2020": 12},
getDifferences = {};

Object.keys(storeA).forEach(function (k) {
getDifferences[k] = storeA[k] - storeB[k];
});

document.write('<pre>' + JSON.stringify(getDifferences, 0, 4) + '</pre>');

更多例子

in storeX obj and storeY obj. { '4100': 3060431, '4130': 4413045, '16386': 4191921, '17476': 4161761 } { '4100': 3332286, '4130': 7640173, '16386': 5773080, '17476': 4692493 }

var storeA = { '4100': 3060431, '4130': 4413045, '16386': 4191921, '17476': 4161761 },
storeB = { '4100': 3332286, '4130': 7640173, '16386': 5773080, '17476': 4692493 },
getDifferences = {};

Object.keys(storeA).forEach(function (k) {
getDifferences[k] = Math.abs(storeA[k] - storeB[k]);
});

document.write('<pre>' + JSON.stringify(getDifferences, 0, 4) + '</pre>');

关于Javascript 玩对象项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36931543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com