Getting data from graphql, example:
const data = [
{
items: [
{
link: '/monday',
name: 'Monday',
},
{
link: '/tuesday',
name: 'Tuesday',
},
{
link: '/wednesday',
name: 'Wednesday',
},
],
},
{
items: [
{
link: '/january',
name: 'January',
},
{
link: '/february',
name: 'February',
},
{
link: '/march',
name: 'March',
},
],
},
]
I'm trying to build a new object and also add a unique id
but it takes me two loops to accomplish (also includes expected output):
const data = [
{
items: [
{
link: '/monday',
name: 'Monday',
},
{
link: '/tuesday',
name: 'Tuesday',
},
{
link: '/wednesday',
name: 'Wednesday',
},
],
},
{
items: [
{
link: '/january',
name: 'January',
},
{
link: '/february',
name: 'February',
},
{
link: '/march',
name: 'March',
},
],
},
]
let itemsObj = []
let merge = []
data.forEach(section => {
section.items.forEach((item, i) => {
return (itemsObj = [...itemsObj, item])
})
})
itemsObj.map((item, i) => {
item.id = i
return merge.push(item)
})
console.log(itemsObj)
Code that correctly builds what I need but takes a foreach
and map
:
data.forEach(section => {
section.items.forEach((item, i) => {
return (itemsObj = [...itemsObj, item])
})
})
itemsObj.map((item, i) => {
item.id = i
return merge.push(item)
})
When I try to add an incremented id
in one loop it starts over, example:
const data = [
{
items: [
{
link: '/monday',
name: 'Monday',
},
{
link: '/tuesday',
name: 'Tuesday',
},
{
link: '/wednesday',
name: 'Wednesday',
},
],
},
{
items: [
{
link: '/january',
name: 'January',
},
{
link: '/february',
name: 'February',
},
{
link: '/march',
name: 'March',
},
],
},
]
let itemsObj = []
data.forEach(section => {
section.items.forEach((item, i) => {
item.id = i
return (itemsObj = [...itemsObj, item])
})
})
console.log(itemsObj)
Code trying to add the id
and build the object in one loop that causes the id
to start over:
let itemsObj = []
data.forEach(section => {
section.items.forEach((item, i) => {
item.id = i
return (itemsObj = [...itemsObj, item])
})
})
console.log(itemsObj)
Per answer same issue occurs with an id
that isn't unique:
data.flatMap(dataObj => {
return dataObj.items.map((item, i) => {
return { i, ...item }
})
})
Expected output example to clarify comment:
[
{
"link": "/monday",
"name": "Monday",
"id": 0
},
{
"link": "/tuesday",
"name": "Tuesday",
"id": 1
},
{
"link": "/wednesday",
"name": "Wednesday",
"id": 2
},
{
"link": "/january",
"name": "January",
"id": 3
},
{
"link": "/february",
"name": "February",
"id": 4
},
{
"link": "/march",
"name": "March",
"id": 5
}
]
Research:
- Add id to array of objects
- Add an incrementing ID property to each object in array after it has been submitted
- Nodejs how to put multiple id's into an if
- Find object by id in an array of JavaScript objects
Is there a way to an id
in one loop instead of using a foreach
and map
?