Home > database >  Editing/Adding value in object of objects
Editing/Adding value in object of objects

Time:07-12

Main problem is that key format is not supported for selecting. I do have automatically generated object list with unique keys. Index and key is known. I do need to add value to custom_property object or edit if it already exists.

Code snapshot:

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": {
  },
  }
  }

I do have these values that I want to insert/update on the custom_property array

const index = 0;
const name = "some_title"
const value = {value: 1, label: "some label"}

How result should look like:

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": {
      },
      }
      }

CodePudding user response:

You can try using Object.values() and get the array of items and then pass down the index like,

Object.values(data)[index]

Then assign the dynamic key-value to the custom_properties like,

item.custom_properties = {
  [name]: value,
};

Working Snippet:

  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));

CodePudding user response:

you can do something like this

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)

  • Related