[英]Editing/Adding value in object of objects
主要問題是不支持選擇密鑰格式。 我確實已經自動生成了帶有唯一鍵的對象列表。 索引和鍵是已知的。 我確實需要為 custom_property 對象添加值,或者如果它已經存在則進行編輯。
代碼快照:
let initialValue = {
"126ccbb5-1a89-40a9-9393-6849a2f502bc": {
"uuid": "126ccbb5-1a89-40a9-9393-6849a2f502bc",
"order": 0,
"custom_properties": {
},
},
"82945a12-ffcb-4dba-aced-e201fa9a531e": {
"uuid": "82945a12-ffcb-4dba-aced-e201fa9a531e",
"order": 1,
"custom_properties": {
},
}
}
我確實有這些值,我想在 custom_property 數組上插入/更新
const index = 0;
const name = "some_title"
const value = {value: 1, label: "some label"}
結果應該如何:
let initialValue = {
"126ccbb5-1a89-40a9-9393-6849a2f502bc": {
"uuid": "126ccbb5-1a89-40a9-9393-6849a2f502bc",
"order": 0,
"custom_properties": {
"some_title" : {value: 1, label: "some label"}
},
},
"82945a12-ffcb-4dba-aced-e201fa9a531e": {
"uuid": "82945a12-ffcb-4dba-aced-e201fa9a531e",
"order": 1,
"custom_properties": {
},
}
}
你可以做這樣的事情
const update = (data, index, key, value) => Object.fromEntries(Object.entries(data).map(([k, v], i) => i === index? [k, {...v, custom_properties: Object.assign({}, v.custom_properties, {[key]: value})}]:[k,v])) let initialValue = { "126ccbb5-1a89-40a9-9393-6849a2f502bc": { "uuid": "126ccbb5-1a89-40a9-9393-6849a2f502bc", "order": 0, "custom_properties": {}, }, "82945a12-ffcb-4dba-aced-e201fa9a531e": { "uuid": "82945a12-ffcb-4dba-aced-e201fa9a531e", "order": 1, "custom_properties": {}, } } const newValue = update(initialValue, 0, 'newKey', 'newValue') console.log(newValue)
您可以嘗試使用Object.values()並獲取項目數組,然后傳遞索引,例如,
Object.values(data)[index]
然后將動態鍵值分配給custom_properties
,例如,
item.custom_properties = {
[name]: value,
};
工作片段:
let initialValue = { '126ccbb5-1a89-40a9-9393-6849a2f502bc': { uuid: '126ccbb5-1a89-40a9-9393-6849a2f502bc', order: 0, custom_properties: {}, }, '82945a12-ffcb-4dba-aced-e201fa9a531e': { uuid: '82945a12-ffcb-4dba-aced-e201fa9a531e', order: 1, custom_properties: {}, }, }; const index = 0; const name = 'some_title'; const value = { value: 1, label: 'some label' }; const getUpdatedResult = (data) => { const item = Object.values(data)[index]; if (item) { item.custom_properties = { [name]: value, }; } return data; }; console.log(getUpdatedResult(initialValue));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.