javascript - Pushing data to (nested) array, depending on existing object field -
i'm pushing data array within foreach-loop:
let result = []; data.foreach(function(part){ let text = part.one + part.two; result.push({ text: text, element: [{ id: part._id, page: part.page }] }); });
but need check if text
in object of array.
if there such object, page part.page
should added array of object identical text field. otherwise data should added result array.
example
result = [ { text: 'some text', element: [{ id: 1, page: '12-34'}] } ]
if next part
-elements this:
{ id: 2, one: 'some ', two: 'text', page: '45-67' } { id: 3, one: 'another ', two: 'text', page: '12-34' }
result
should get
result = [ { text: 'some text', pages: [{ id: 1, page: '12-34'}, { id: 2, page: '45-67' }] // page added array, text identical }, { text: 'another text', pages: [{ id: 3, page: '12-34'}] } ]
additional question
is possible sort result array first text
-field , second element-objects page
-field?
this wrong order first object:
[{ id: 2, page: '45-67'}, { id: 1, page: '12-34' }]
...and 'another text' should before 'some text'
you can use find
check if element exists. in case use findindex
updating nested array:
let index = result.findindex(x => x.reference === reference); if (index === -1) { result.push({ text: text, element: [ { id: part._id, page: part.page } ] }); } else { result[index].element.push( { id: part._id, page: part.page } ); }
Comments
Post a Comment