如何在数组的最后一项之前插入json?

kmynzznz  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(351)

我想构建一个总是插入的函数 JSON Itemslast 前一项。

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);

输出:

[ [ { 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 } ]

预期产出:

[ 
  { India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' } },
  { USA: { Score: '15', PlayedMatched: '06' } },
  [ { Japan: [Object] }, { Japan: [Object] } ],      //At here
  { 'Index Value': 12 }
]

我该怎么做?我还想删除以下内容: [] 在我的输出结果中:)
这样地:

[ 
  {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 }      
]
chhkpiq4

chhkpiq41#

只需将要插入的索引号作为 index 用于完成作业的insert函数中的参数。你的情况是最后一名,所以你可以通过 array.length - 1 ```
const array = [
{India: { Score: '12', PlayedMatched: '21' } },
{ China: { Score: '52', PlayedMatched: '51' }},
{ USA: { Score: '15', PlayedMatched: '06' } },
{ '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" } }];

const result = insert(array,array.length - 1,insertItems)

console.log(result);

7bsow1i6

7bsow1i62#

按如下方式使用拼接功能:

const array = [ 
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Index Value': 12 }      
]

var insertItems= [{ 'Japan': { Score: "54", PlayedMatched: "56" } },{ 'Russia': { Score: "99", PlayedMatched: "178" } }];

array.splice(array.length - 1, 0, ...insertItems)

console.log(array);

请注意,splice会修改您提供给它的同一阵列,而不会创建该阵列的修改副本。

相关问题