根据键:值添加新对象



我有一个对象,我想根据did值在每个对象之前添加一个新对象。我尝试的内容如下,但不是我想要的,它为每个项目添加,并且还变成了数组。

let obj = {
"district": [{
"id": 1,
"uid": 1,
"type": 3,
"pid": 0,
"cid": 0,
"did": 1,
"name": "text 1"
},
{
"id": 2,
"uid": 2,
"type": 3,
"pid": 0,
"cid": 0,
"did": 2,
"name": "text 2"
},
{
"id": 3,
"uid": 3,
"type": 3,
"pid": 0,
"cid": 0,
"did": 2,
"name": "text 3"
},
{
"id": 4,
"uid": 4,
"type": 3,
"pid": 0,
"cid": 0,
"did": 3,
"name": "text 4"
},
{
"id": 5,
"uid": 5,
"type": 3,
"pid": 0,
"cid": 0,
"did": 3,
"name": "text 5"
},
{
"id": 6,
"uid": 6,
"type": 3,
"pid": 0,
"cid": 0,
"did": 0, // should not add object before this becaus did is 0
"name": "text 6"
}
]
}
var result = obj.district.map(function(el) {
if(el.did > 0){
var o = Object.assign({}, obj.district);
o.divider = {
"dv": true,
"name": 'divider ' + el.did
};
return o;
}
})
console.log(result)

如果值不是 null 或 0,则添加新对象did有点> 0。 结果应该是这样的:

let obj = {
"district": [{
"dv": true,
"name": "divider 1"
}, {
"id": 1,
"uid": 1,
"type": 3,
"pid": 0,
"cid": 0,
"did": 1,
"name": "text 1"
},
{
"dv": true,
"name": "divider 2"
},
{
"id": 2,
"uid": 2,
"type": 3,
"pid": 0,
"cid": 0,
"did": 2,
"name": "text 2"
},
{
"id": 3,
"uid": 3,
"type": 3,
"pid": 0,
"cid": 0,
"did": 2,
"name": "text 3"
},
{
"dv": true,
"name": "divider 3"
},
{
"id": 4,
"uid": 4,
"type": 3,
"pid": 0,
"cid": 0,
"did": 3,
"name": "text 4"
},
{
"id": 5,
"uid": 5,
"type": 3,
"pid": 0,
"cid": 0,
"did": 3,
"name": "text 5"
},
{
"id": 6,
"uid": 6,
"type": 3,
"pid": 0,
"cid": 0,
"did": 0, // should not add object before this becaus did is 0
"name": "text 6"
}
]
}
console.log(obj)

它应该在具有公共didid 的对象之前添加,例如,如果有 5 个项目带有 2did,它应该只添加新对象一次,而不是为每个项目。 此外,新值的名称应基于didid、分隔符 1、分隔符 2 或 .。

试试这个:

var lastDivider;
var result = {
district: []
}
obj.district.forEach(function(el) {
if (el.did > 0 && lastDivider !== el.did) {
result.district.push({
"dv": true,
"name": 'divider ' + el.did
});
lastDivider = el.did;
}
result.district.push([Object.assign({}, el)]);
});

最新更新