0
伙计们,您可以帮助完成对象的自定义。我想索引正确的对象,但对象的当前输出是索引是商店的ID。javascript中的自定义多维对象
样本对象
var stocks = [
{
"size": "2",
"count": 5,
"store": {
"id": 3,
"title": "Belconnen"
}
},
{
"size": "3",
"count": 4,
"store": {
"id": 4,
"title": "Canberra"
}
},
{
"size": "4",
"count": 4,
"store": {
"id": 5,
"title": "Bankstown"
}
},
{
"size": "5",
"count": 5,
"store": {
"id": 4,
"title": "Canberra"
}
}];
电流输出
{
0: {
"sizes": {
2: 3,
3: 0,
4: 0,
5: 0
}
}
},
{
1: {
"sizes": {
2: 0,
3: 3,
4: 0,
5: 0
}
}
},
{
2: {
"sizes": {
2: 0,
3: 0,
4: 3,
5: 0
}
}
},
{
3: {
"sizes": {
2: 0,
3: 0,
4: 0,
5: 3
}
}
}
我当前的代码
var result = function (data) {
var stores = {},
sizes = Object.create(null),
i = 0;
data.forEach(function (item) {
var index = i;
if (!stores[index]) {
stores[index] = { sizes: {} };
Object.keys(sizes).forEach(function (key) {
stores[index].sizes[key] = 0;
});
}
if (!sizes[item.size]) {
Object.keys(stores).forEach(function (key) {
stores[key].sizes[item.size] = 0;
sizes[item.size] = true;
});
}
stores[index].sizes[item.size] = item.count;
i++;
});
return stores;
}(stocks);
console.log(result);
我的期望输出
{
0: {
"sizes": {
2: 3,
3: 0,
4: 0,
5: 0
}
}
},
{
1: {
"sizes": {
2: 0,
3: 3,
4: 0,
5: 3
}
}
},
{
2: {
"sizes": {
2: 0,
3: 0,
4: 3,
5: 0
}
}
}
在此先感谢。
*“我想索引对象正确”*是什么意思?你的逻辑是什么? – RomanPerekhrest
如果我把你在小提琴中提供的代码给了我预期的输出。 [Object Reorganize](https://jsfiddle.net/qsxzrmt2/1/)。你能给我关于你的JavaScript文件的更多信息吗?你如何通过股票对象? –
你能否请求提供关于你试图实现的逻辑的更多信息?外部物体的标志是什么?大小对象中键的值应该是多少?如何映射在一起?我的输出也得到了不同的结果。在你列出的输出和你的预期输出中,你总是有3个,但看起来应该是5,4,4,5? –