在数组中添加元素嵌入数组- Javascript我有以下数组:
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
,并且在该数组中,其中的每个数组看起来如下所示:
0 : {_id: "bla", header: "test", time: "test PM", content: "test", uniqueid: "test"}
1: {_id: "blay", header: "tests", time: "tests PM", content: "even more tests", uniqueid: "tests"}
2: {_id: "awa", header: "sd", time: 3:14:15 PM", content: "sdf", uniqueid: "sdfg"}
我的问题是,我如何在这个大数组中插入另一个“小数组”,在位置0,header: finaltest,time: finalTest PM,content: thefinaltest和唯一I: testt?
我在想也许可以使用.unshift,但我不确定。
发布于 2020-12-18 15:35:33
嗨,你是说像这样的东西吗?
let table = [
{_id: "bla", header: "test", time: "test PM", content: "test", uniqueid: "test"},
{_id: "blay", header: "tests", time: "tests PM", content: "even more tests", uniqueid: "tests"},
{_id: "awa", header: "sd", time: "3:14:15 PM", content: "sdf", uniqueid: "sdfg"}
]
let newRow = {_id: "bl@@@@", header: "finaltest", time: "finalTest PM", content: "test", uniqueid: "testt"};
table.unshift(newRow);
console.log(table);
发布于 2020-12-18 15:33:29
如果你想创建一个新的数组,而不是改变现有的数组,你可以使用扩展运算符:
const originalArray = [{}, {}, {}, {}]
const newObj = { some: 'values' }
const newArray = [newObj, ...originalArray]
结果:
// newArray
[{ some: 'values' }, {}, {}, {}, {}]
发布于 2020-12-18 15:35:52
Javascript的splice()方法可以提供帮助。就这么简单:
const data = [
{ _id: "bla", header: "test", time: "test PM", content: "test", uniqueid: "test" },
{ _id: "blay", header: "tests", time: "tests PM", content: "even more tests", uniqueid: "tests" },
{ _id: "awa", header: "sd", time: "3:15 PM", content: "sdf", uniqueid: "sdfg" }
];
const inserted_obj = { _id: "inserted", header: "finaltest", time: "finalTest PM", content: "thefinaltest", uniqueid: "testt" };
let start = 0;
let deleteCount = 0;
data.splice(start, deleteCount, inserted_obj);
console.log(data);
https://stackoverflow.com/questions/65359611
复制