0

Here is my JSON:

{
  "language": "eng",
  "plugins": {
    "search": false,
    "import-xml": false,
    "export-xml": false,
    "import-pdf": false,
    "export-pdf": false
  },
  "tabs": {
    "general": {
      "arm": "Գլխավոր",
      "rus": "Главный",
      "eng": "General",
      "documentTitle": {
        "arm": "Փաստաթղթի Անվանումը",
        "rus": "Заголовок Документа",
        "eng": "Document Title"
      },
      "sections": {
        "14656691": {
          "type": "field-section",
          "title": "",
          "elements": {
          },
          "collapse": false
        },
        "06558184": {
          "type": "table-section",
          "title": "",
          "elements": {
          },
          "collapse": false
        }
      }
    },
    "custom-19588079": {
      "arm": "Custom",
      "rus": "Custom",
      "eng": "Custom",
      "documentTitle": {
        "arm": "Փաստաթղթի Անվանումը",
        "rus": "Заголовок Документа",
        "eng": "Document Title"
      },
      "sections": {
      }
    }
  }
}

For example I want to add new object in general sections object. How can I do it?

I tried to do something like this, but it doesn't work properly:

let config = {} (my object);

config = {...config.general.sections, ...{new object}}

but config result is config.general.sections object.

4
  • Why is that surprising? You're explicitly replacing config with a shallow copy of config.general.sections plus whatever's in "new object". Commented May 15, 2020 at 17:04
  • Update it as config.tabs.general.sections = {...config.tabs.general.sections, ...{new object}} Commented May 15, 2020 at 17:05
  • How about Object.assign(config.tabs.general.sections, newObject)? Commented May 15, 2020 at 17:10
  • same result the problem is in localStorage that json is on localStorage Commented May 15, 2020 at 17:13

3 Answers 3

0

try to do this:

let config = {} (my object);
let newObject = {"newKey":"newValue"};
config.general.newSection = newObject;
console.log(config);

Or try this:

let config = {} (my object);
let newObject = {"newKey":"newValue"};
config['general']['newSection'] = newObject;
console.log(config);

I home it's works

Sign up to request clarification or add additional context in comments.

Comments

0

There is a simple way, to merge with a new section and to reassign it:

config.tabs.general.sections = {
  ...config.tabs.general.sections,
  newSection: {},
};

Here is a good explanation https://dmitripavlutin.com/object-rest-spread-properties-javascript/

Comments

0

This code is very useful if you know the path to the wanted value.

https://stackoverflow.com/a/66440832/1602673

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.