I currently have an object that looks like:
var account = [
{"Id":"A1",
"item":"123,456,789"}
];
Since the object above has the key item
with multiple values separated by ,
, I'd like to create a new array with:
[{"Id":"A1",
"item":"123"},
{"Id":"A1",
"item":"456"},
{"Id":"A1",
"item":"789"}
]
I'm not sure if there's a function for this specific type of array split, since the value of the key item
is separated by commas.
CodePudding user response:
You could use Array.flatMap()
along with String.split()
and Array.map()
to get the desired result.
const account = [ { "Id":"A1", "item":"123,456,789" } ];
const result = account.flatMap(({ Id, item }) => {
return item.split(',').map(item => ({ Id, item }))
});
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
CodePudding user response:
account.item.split(',') see this it should work
CodePudding user response:
This is a readable response I think.
function format(account) {
let array = [];
for (let i = 0; i < account.length; i ) {
let item = account[i].item.split(',');
for (let j = 0; j < item.length; j ) {
array.push({ Id: account[i].Id, item: item[j] });
}
}
return array;
}