El problema principal es que el formato de clave no es compatible para seleccionar. Tengo una lista de objetos generada automáticamente con claves únicas. El índice y la clave son conocidos. Necesito agregar valor al objeto custom_property o editarlo si ya existe.
Instantánea de código:
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": { }, } }Tengo estos valores que quiero insertar/actualizar en la matriz custom_property
const index = 0; const name = "some_title" const value = {value: 1, label: "some label"}Cómo debería verse el resultado:
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": { }, } }puedes hacer algo como esto
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)Puede intentar usar Object.values() y obtener la matriz de elementos y luego pasar el índice como,
Object.values(data)[index] Luego asigne el valor clave dinámico a custom_properties como,
item.custom_properties = { [name]: value, };Fragmento de trabajo:
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));