[英]Javascript dynamic object similar to PHP multidimensional associative array
How would you dynamically add/update a property of an object in Javascript?您将如何在 Javascript 中动态添加/更新 object 的属性?
For example, with PHP's associative array, it's super simple and intuitive.例如,使用 PHP 的关联数组,它超级简单直观。 eg例如
$test = [];
foreach ($data as $key => $value) {
...
$test[$year][$month] += $amount;
}
var_dump(json_encode($test));
I can automatically update or add new item to the array.我可以自动更新或向数组添加新项目。 I'd get something like:我会得到类似的东西:
{
"2018": {
"5": 1110,
"6": 690
},
"2019": {
"9": 354,
"10": 531,
"12": 567
},
"2020": {
"1": 444,
"2": 100,
"4": 200,
"8": 1431
}
}
I have tried, in Javascript without success:我试过,在 Javascript 没有成功:
let test = {};
data.forEach(function (item, index) {
...
test[year] = {
[month]: amount
}
});
which yield something like:产生类似的东西:
{
"2018": {
"2": 1394000
},
"2019": {
"0": 3204000
},
"2020": {
"0": 1475000
}
}
The month gets replaced by whatever is last in the loop.月份被循环中的最后一个替换。 Also I haven't been able to figure out how to add to the existing amount.此外,我还无法弄清楚如何添加到现有金额。
I'd prefer not to do a bunch of ifs to check if the object property already exists etc.我不想做一堆 ifs 来检查 object 属性是否已经存在等。
Or perhaps I'm approaching this the wrong way?或者也许我以错误的方式接近这个?
Edit:编辑:
Example of $data
or data
, which can have duplicate years and months. $data
或data
的示例,可以有重复的年份和月份。
[
{
"amount": 123,
"year": 2020,
"month": 5
},
{
"amount": 123,
"year": 2019,
"month": 3
},
...
]
Here's a short example of how you can build the test object by looping over the data array:下面是一个简短的示例,说明如何通过循环遍历数据数组来构建测试 object:
const data = [
{
"amount": 10,
"year": 2020,
"month": 5
},
{
"amount": 20,
"year": 2019,
"month": 5
},
{
"amount": 30,
"year": 2019,
"month": 6
}
]
let test = {};
data.forEach(item => {
if (!test[item.year]) {
test[item.year] = {};
}
test[item.year][item.month] = item.amount;
});
console.log(test)
This outputs:这输出:
{
2019: {
5: 20,
6: 30
},
2020: {
5: 10
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.