javascript - 如何在最后一项之前将 JSON 插入数组中?
问题描述
我想构建一个函数,该函数将始终在之前的项目JSON Items
处插入数组。last
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 }
]
解决方案
只需将要插入的索引号作为index
参数传递给插入函数即可完成工作。在你的情况下排名第二,你可以通过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);
推荐阅读
- python - 如何在 numpy mgrid 输入(numpy)上使用变量
- angular - Angular 模板驱动的表单验证:我应该发布 ngModel 还是 form.value?
- java - 添加了 CSV 导出小数点
- javascript - 如何使用javascript从firebase获取特定孩子的所有值?
- c# - 在 EF 6 中模拟 DBContext 无法按预期工作
- java - Fragment 为 onCreateView 时从 Activity 向 Fragment 发送数据
- jquery - 如何知道 Web 应用程序使用哪些框架或库
- java - Git winmerge 弹出“选择文件和文件夹”出现
- r - 在 group_by 之后使用子数据集
- jquery - Cheerio jquery node js:获取href值