我有一个由键值对组成的 javascript 对象,我想在某个位置插入一个键值对,在下面的示例中,我想在第一个键值对之后插入它。

var obj = {key1: "value1", key2: "value2"};

console.log(obj);// {key1: "value1", key2: "value2"}

obj.key3 = "value3";

console.log(obj);// {key1: "value1", key2: "value2", key3: "value3"}

最佳答案

对于在某个索引后添加键值,我们可以使用 Object.entries()Object.fromEntries()

let obj = {key1: "value1", key2: "value2"};
let keyValues = Object.entries(obj); //convert object to keyValues ["key1", "value1"] ["key2", "value2"]
keyValues.splice(1,0, ["newKey","newValue"]); // insert key value at the index you want like 1.
let newObj = Object.fromEntries(keyValues) // convert key values to obj {key1: "value1", newKey: "newValue", key2: "value2"}

关于javascript - 在javascript对象的某个位置插入键值对,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55016950/

10-11 14:17