Ad
JavaScript / Set Increment Index From 0
I have a problem with setting always unique index, incrementing by one.
I have an array like this.
const parentArr = [
{
name: 'first parent array',
childArray: [
{
name: '1 / first child'
},
{
name: '1 / second child'
}
]
},
{
name: 'second parent array',
childArray: [
{
name: '2 / first child array'
},
{
name: '2 / second child array'
}
]
}
]
And I am expecting result like this:
const expectedResult = [
{
name: 'first parrent array',
additionalInfo: [
{
index: 0,
name: '1 - first child'
},
{
index: 1,
name: '1 - second child'
}
]
},
{
name: 'second parrent array',
additionalInfo: [
{
index: 2,
name: '2 -first child array'
},
{
index: 3,
name: '2- second child array'
}
]
}
]
I want to have index inside additionalInfo, for each item from 0.
I tried like this, but I got wrong index number
return parentArr.map((parent) => {
return {
name: parent.name,
additionalData: parent.childArray.map((child, index) => ({
name: child.name
index: index // I'M STUCK ON THIS LINE
})),
};
});
Ad
Answer
You have to manage the index of children independently from the loop. so what about this?
let i = 0;
return parentArr.map((parent) => {
return {
name: parent.name,
additionalData: parent.childArray.map((child) => ({
name: child.name
index: i++
})),
};
});
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad