Reputation: 774
I'm new in React native and I want to add value inside object array inside another object array. I have data like this :
dataAttribute: [
{
id: 1,
title: 'A',
data: [
{ id: '1', name: 'First Name', type: 'text' },
{ id: '2', name: 'Last Name', type: 'text' },
],
},
{
id: 2,
title: 'B',
data: [
{ id: '1', name: 'Twitter', type: 'text' },
{ id: '2', name: 'Twitter follower', type: 'number' },
],
}
]
and i want add params 'statusSelected == true' inside child array like this:
dataAttribute: [
{
id: 1,
title: 'A',
data: [
{ id: '1', name: 'First Name', type: 'text', statusSelected: true},
{ id: '2', name: 'Last Name', type: 'text' },
],
},
{
id: 2,
title: 'B',
data: [
{ id: '1', name: 'Twitter', type: 'text' },
{ id: '2', name: 'Twitter follower', type: 'number' },
],
}
]
Upvotes: 1
Views: 1767
Reputation: 523
try this
dataAttribute = [
{
id: 1,
title: 'A',
data: [
{ id: '1', name: 'First Name', type: 'text' },
{ id: '2', name: 'Last Name', type: 'text' },
],
},
{
id: 2,
title: 'B',
data: [
{ id: '1', name: 'Twitter', type: 'text' },
{ id: '2', name: 'Twitter follower', type: 'number' },
],
}
]
const changeMe = (dataAttribute, attrId, dataId) => dataAttribute.map(x => x.id === attrId ? {...x, data: x.data.map(y => y.id === dataId ? {...y, statusSelected: true} : y)} : x)
console.log(changeMe(dataAttribute, 1, "1"))
output:
[ { "id": 1, "title": "A", "data": [ { "id": "1", "name": "First Name", "type": "text", "statusSelected": true }, { "id": "2", "name": "Last Name", "type": "text" } ] }, { "id": 2, "title": "B", "data": [ { "id": "1", "name": "Twitter", "type": "text" }, { "id": "2", "name": "Twitter follower", "type": "number" } ] }
Attached JsFiddle for result.
Upvotes: 3
Reputation: 360
You can map over the array until you find the element where you want to add the extra data. Assuming you know the id and sub id where you want to add the info:
const updatedDataAttribute = dataAttribute.map((item) => {
if (item.id === <desired item id>) {
return {
...item,
data: item.data.map((datum) => {
if (datum.id === <desired sub item id>) {
return {
...datum,
statusSelected: true,
}
}
return datum
}),
}
}
return item
})
Upvotes: 2
Reputation: 30390
A simple way to achieve this is to simply mutate the object, by defining the statusSelected
attribute as true
on the first item of the data array.
So, suppose you have dataAttribute
defined in an object like so:
var object = {
dataAttribute: [
{
id: 1,
title: 'A',
data: [
{ id: '1', name: 'First Name', type: 'text' },
{ id: '2', name: 'Last Name', type: 'text' },
],
},
{
id: 2,
title: 'B',
data: [
{ id: '1', name: 'Twitter', type: 'text' },
{ id: '2', name: 'Twitter follower', type: 'number' },
],
}
]
}
// add statusSelected to the first item of the nested data array
object.dataAttribute[0].data[0].statusSelected = true;
This will produce the updated object that you need.
Upvotes: 0