I have an object, I want to add a new object before each object based on did value. What I tried is below, but it not what I want, it add for each item, and also it turned into array.
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)
Add new object if did value is not null or 0, kinda > 0. the result should be like this:
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)
It should add before object with common did id, for example if there is 5 item with did 2, it should just add new object once, not for each item. also name of new value should be based on did id, divider 1, divider 2 or ..
idproperty, why not use that instead and create a new array containing that unique identifier?containing that unique identifier?I have no idea what result will be output | maybe I choose wrong idea to do this, but I think this format is only way that solve my issue. what I really want is divide item based ondid|did=> mean s=> district id, I want to use this for drop down, and my drop down not support optgroup