I am looking to create a function that can consistently add JSON Items
to an array just before the last item.
const array = [
{India: { Score: '12', PlayedMatched: '21' } },
{ China: { Score: '52', PlayedMatched: '51' }},
{ USA: { Score: '15', PlayedMatched: '06' } },
// Insert Items Here
{ 'Index Value': 12 }
]
const insert = (arr, index, newItem) => [
...arr.slice(0, index),
newItem,
...arr.slice(index)
]
var insertItems= [{ 'Japan': { Score: "54", PlayedMatched: "56" } },{ 'Russia': { Score: "99", PlayedMatched: "178" } }];
// I have tried like this: array.slice(-1) to insert item one step before always
const result = insert(array,array.slice(-1),insertItems)
console.log(result);
OutPut:
[ [ { Japan: [Object] }, { Japan: [Object] } ], //Not at Here
{ India: { Score: '12', PlayedMatched: '21' } },
{ China: { Score: '52', PlayedMatched: '51' } },
{ USA: { Score: '15', PlayedMatched: '06' } },
{ 'Index Value': 12 } ]
Expected Output:
[
{India: { Score: '12', PlayedMatched: '21' } },
{ China: { Score: '52', PlayedMatched: '51' }},
{ USA: { Score: '15', PlayedMatched: '06' } },
[ { Japan: [Object] }, { Japan: [Object] } ], //At here
{ 'Index Value': 12 }
]
What is the correct way to achieve this? Also, how can I remove the square brackets [] in my output results? :)
Like This:
[
{India: { Score: '12', PlayedMatched: '21' } },
{ China: { Score: '52', PlayedMatched: '51' }},
{ USA: { Score: '15', PlayedMatched: '06' } },
{ 'Japan': { Score: "54", PlayedMatched: "56" } },
{ 'Russia': { Score: "99", PlayedMatched: "178" } },
{ 'Index Value': 12 }
]