I have data in the form of array of object i.e data and I want to push the value from data to another array of object i.e catArrObj on the basis of similar value of fields inside two of them.
catArrObj
catArrObj=[
{
name:"one",
tags:[]
},
{
name:"two",
tags:[]
}
]
I want to push the value on the basis of the name of catArrObj inside the tags of catArrObj, I am using the data to push the value which have categories matching with the name of catArrObj.
data
data= [
{
"tag_name": "US",
"id": 1,
"categories": "one"
},
{
"tag_name": "US-CA",
"id": 2,
"categories": "one"
},
{
"tag_name": "Full Time",
"id":3,
"categories": "two"
}
]
logic
for(let i=0; i<catArrObj.length; i++){
for(let index=0; index<data.length; index++){
if(catArrObj[i].name === data[index].categories){
let singleTag = {
name: data[index].categories,
value: data[index].tag_name,
id: data[index].id,
checked: false,
}
catArrObj[i].tags.push(singleTag)
}
}
console.log(catArrObj)
I should get the required output as this
[
{
name:"one",
tags:[
{
checked: false
id: 1
name: "one"
value: "US"
},
{
checked: false
id: 2
name: "one"
value: "US-CA"
},
]
},
{
name:"two",
tags:[
{
checked: false
id: 1
name: "two"
value: "Full Time"
}
]
}
]
but, I am getting this
[
{
name:"one",
tags:[
{
checked: false
id: 1
name: "one"
value: "US"
},
{
checked: false
id: 2
name: "one"
value: "US-CA"
},
{
checked: false
id: 1
name: "two"
value: "Full Time"
}
]
},
{
name:"two",
tags:[
{
checked: false
id: 1
name: "one"
value: "US"
},
{
checked: false
id: 2
name: "one"
value: "US-CA"
},
{
checked: false
id: 1
name: "two"
value: "Full Time"
}
]
}
]
why are all the three values getting pushed in both the objects? I have tried many approaches but I am not able to get the desired output.
also, the data is dynamic, means I can have any number of objects inside it with having various categories and the catArrObj will have objects equal to unique categories inside data.