1

I am struggling to push one object into another. I have a multidimensional JSON object like

{
   "item1":{
      "key":"Value",
      "key":"Value"
   },
   "item2":{
      "key":"Value",
      "key":"Value"
   },
   "item3":{
      "key":"Value",
      "key":"Value",
      "subItem3":{
         "key":"Value",
         "key":"Value"
      }
   }
}

I want to push item3 in item2 like

{
   "item1":{
      "key":"Value",
      "key":"Value"
   },
   "item2":{
      "key":"Value",
      "key":"Value",
      "item3":{
         "key":"Value",
         "key":"Value",
         "subItem3":{
            "key":"Value",
            "key":"Value"
         }
      }
   }
}

How to achieve that any help will be appreciated.

3 Answers 3

2

The question is vague at the moment. And the given input object is wrong. An object cannot have duplicate properties. Adjusting for these errors, you could probably use Object.entries() to get an iterable array of the object and use Array#reduce on it to transform it to the required form

Try the following

const input = {
  "item1": {
    "key1": "Value1",
    "key2": "Value2"
  },
  "item2": {
    "key1": "Value1",
    "key2": "Value2"
  },
  "item3": {
    "key1": "Value1",
    "key2": "Value2",
    "subItem3": {
      "key1": "Value1",
      "key2": "Value2"
    }
  }
};

const output = Object.entries(input).reduce((acc, [key, value]) => {
  if (key === 'item3')
    acc['item2'] = { ...acc['item2'], [key]: value };
  else 
    acc[key] = value;
  return acc;
}, Object.create(null));

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0px }

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

Comments

0

Let's say it's in a variable myObject.

myObject.item2.item3 = myObject.item3;
delete myObject.item3;

Comments

0

try this way.

let items = {
       "item1":{
          "key":"Value",
          "key":"Value"
       },
       "item2":{
          "key":"Value",
          "key":"Value"
       },
       "item3":{
          "key":"Value",
          "key":"Value",
          "subItem3":{
             "key":"Value",
             "key":"Value"
          }
       }
    }

    items.item2.item3 = items.item3
    delete items.item3

    console.log(items)

1 Comment

That's wrong because you're not preserving the properties that were already in item2. See my answer. We had the same idea around the same time.

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.