具有以下格式的对象:
let obj = {
p2: {
p21: [
{
key1: "val1",
value1: "val2"
},
{
prop: "test",
value: "dummy"
}
]
}
}
我基本上必须查看是否有一个具有键“ prop”的对象,并用传递的值替换。如果不存在该键,则用{ "prop" : "test" , value: passed_value}
创建一个对象并将其添加到p21数组中。同样,包含键“ prop”的对象也可以出现在p21数组内的任何位置]
应该是这样的
function checkAndUpdate(replacingValue) {
if(obj's p21 has key name "prop")
{
//update its "value" to the passed "replacingValue"
}
else //if "prop" key not present
{
// create an object with { "prop": "test" , value: replacingValue} and add it to p21 array
}
}
尝试过以下操作:
obj.p2.p21.map((elem) => {
if(Object.keys(elem)[0] === "prop")
elem.value = updateValue;
})
使用.findIndex
查找匹配对象的索引。如果存在,则在数组前后放置.slice
数组,并在中间插入更新的对象。否则,只需将对象散布到数组中即可:
let obj = {
"p2": {
"p21": [{
"key1": "val1",
"value1": "val2",
},
{
"prop": "test",
"value": "dummy"
}
]
}
}
function checkAndUpdate(value) {
const newObj = { prop: 'test', value}
const arr = obj.p2.p21;
const index = arr.findIndex(obj => obj.hasOwnProperty('prop'));
const newArr = index !== -1
? [...arr.slice(0, index), newObj, ...arr.slice(index + 1)]
: [...arr, newObj];
const fullNewObj = {
...obj,
p2: {
...obj.p2,
p21: newArr
}
};
return fullNewObj;
}
console.log(checkAndUpdate('foo'));
还要检查value
是否未定义,如果需要,则从数组中删除匹配的对象,只需进行适当的if
检查,并根据需要对数组进行切片:
let obj = {
"p2": {
"p21": [{
"key1": "val1",
"value1": "val2",
},
{
"prop": "test",
"value": "dummy"
}
]
}
}
function checkAndUpdate(value) {
const newObj = { prop: 'test', value}
const arr = obj.p2.p21;
const index = arr.findIndex(obj => obj.hasOwnProperty('prop'));
const newArr = (() => {
if (index === -1) {
if (value === undefined) {
return arr;
}
return [...arr, newObj];
}
if (value === undefined) {
return [...arr.slice(0, index), ...arr.slice(index + 1)];
}
return [...arr.slice(0, index), newObj, ...arr.slice(index + 1)];
})();
const fullNewObj = {
...obj,
p2: {
...obj.p2,
p21: newArr
}
};
return fullNewObj;
}
console.log(checkAndUpdate('foo'));
您可以使用Array.find
查找hasOwnProperty
prop
并更新的对象
let obj = {
"p2": {
"p21": [{
"key1": "val1",
"value1": "val2",
},
{
"prop": "test",
"value": "dummy"
}
]
}
}
function rep(value) {
if (!value.length) {
obj.p2.p21 = [...obj.p2.p21].filter(e => e.hasOwnProperty('prop'));
return;
}
let ele = obj.p2.p21.find(e => e.hasOwnProperty('prop'));
if (ele) {
ele.value = value
return;
}
obj.p2.p21.push({
"prop": "test",
value
})
}
rep('test');
console.log(JSON.stringify(obj))
rep('');
console.log(JSON.stringify(obj))