I have an array of object. One object has an array inside.
var array = [{ a:'ai', b:'bi', c:['first','second','third']}]
I need to have above array to be like this:
[
[{ a:'ai', b:'bi', c:['first','second','third'], cSplit:'first'}],
[{ a:'ai', b:'bi', c:['first','second','third'], cSplit:'second'}],
[{ a:'ai', b:'bi', c:['first','second','third'], cSplit:'third'}]
]
I tried this code:
var array = [{ a:'ai', b:'bi', c:['first','second','third']}]
var newArr = [];
for( var i=0; i<array[0]['c'].length; i++ ){
var innerArr = array;
innerArr[0]['cSplit'] = array[0]['c'][i];
newArr.push(innerArr);
}
console.log('newArr', newArr)
But it shows:
[
[{a: "ai", b: "bi", c: ['first','second','third'] , cSplit: "third"}],
[{a: "ai", b: "bi", c: ['first','second','third'] , cSplit: "third"}],
[{a: "ai", b: "bi", c: ['first','second','third'] , cSplit: "third"}]
]
Why cSplit doesn't get the first and second value?
Sven.hig
4,5292 gold badges10 silver badges18 bronze badges
asked Jul 28, 2020 at 18:53
Atousa Darabi
9472 gold badges11 silver badges33 bronze badges
4 Answers 4
let array = [{ a:'ai', b:'bi', c:['first','second','third']}]
let newArr = [];
for(let i = 0; i < array[0]['c'].length; i++ ) {
newArr.push({ ...array[0], cSplit: array[0].c[i] })
}
console.log(newArr)
answered Jul 28, 2020 at 19:02
AlexAV-dev
1,1756 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Try with this code
var array = [{ a:'ai', b:'bi', c:['first','second','third']}]
let result = array[0].c.reduce((acc, current) => {
return acc.concat({...array[0], csplit: current})
}, [])
console.log(result);
answered Jul 28, 2020 at 19:04
Yves Kipondo
5,7031 gold badge22 silver badges34 bronze badges
6 Comments
Axnyff
It looks like you're using reduce to do a map.
Yves Kipondo
I use reduce to create a completely new array instead of updating the existing one
Axnyff
map does not mutate either
Yves Kipondo
map will return a new array of course, as the array on which the map should be perform is the value of array[0].c to have access to all the value. if You perform map on the value of array directly you'll have access to one item which is an Object and not first, second and firstAxnyff
array[0].c.map(current => ({...array[0], csplit: current}) ) |
A different approach using map
var array = [{ a:'ai', b:'bi', c:['first','second','third']}]
var res = array.map((o)=>{return Object.values(o)[2].map(e => {
var newob = {...o}
newob.cSplit = e
return newob
})
})
console.log(res)
answered Jul 28, 2020 at 19:11
Sven.hig
4,5292 gold badges10 silver badges18 bronze badges
Comments
This can be succinctly done with Array.prototype.map:
const array = [{ a:'ai', b:'bi', c:['first','second','third']}]
const result = array[0].c.map(c => [{...array[0], cSplit: c}])
console.log(result)
answered Jul 28, 2020 at 19:14
tony19
140k24 gold badges281 silver badges354 bronze badges
Comments
lang-js
array[0].