1

How to append one json object into another json object in reactjs?

My json format from the console is below

Json 1 :

{
 "results": {
             "Action": "Success!"
 },
 "report": {
             "Strategy": "Yes",
             "Plan": "No"
  }
}

Json 2 :

{
     "results": {
                 "Actions": "Failure!"
     },
     "report": {
                 "Idea": "Yep",
                 "Storm": "Nope"
      }
 }

Appended JSON(Desired output format) :

{
     "results": {
                 "Action": "Success!",
                 "Actions": "Failure!"
     },
     "report": {
                 "Strategy": "Yes",
                 "Plan": "No",
                 "Idea": "Yep",
                 "Storm": "Nope"
      }
}
2
  • why do you need to create an object with two similar keys? It should be array of object, I guess. The moment someone parses your JSON, the duplicate keys will be merged. Commented Oct 24, 2020 at 18:36
  • I have edited my question, I am new to react, that is why I could not convey it exactly. Commented Oct 24, 2020 at 18:38

3 Answers 3

1

You can combine two objects

const json1 = {
  "results": {
    "Action": "Success!"
  },
  "report": {
    "Strategy": "Yes",
    "Plan": "No"
  }
};

const json2 = {
  "results": {
    "Actions": "Failure!"
  },
  "report": {
    "Idea": "Yep",
    "Storm": "Nope"
  }
};

let res = Object.keys(json1).reduce((a, key) => {
  a[key] = { ...json2[key], ...json1[key] }
  return a
}, {});

console.log(res)
Sign up to request clarification or add additional context in comments.

Comments

1

You could loop through the object and merge it together.

const firstJsonObject = JSON.parse(firstJson);
const secondJsonObject = JSON.parse(secondJson);

let res = {};

Object.keys(firstJsonObject).forEach(key => {
  res[key] = { ...firstJson[key], ...secondJsonObject[key] };
});

console.log(JSON.stringify(res))

Comments

0

Key can't be duplicate that's why I don't think it's the right way to merge two objects. If you try to merge last(latest) will replace previous fields(keys).

If you want your output as you mentioned. in that case, you need to change the key field name.

JavaScript objects cannot have duplicate keys. The keys must all be unique.

Improved

let obj1 = {
 "results": {
      "Action": "Success!"
 },
 "report": {
       "Strategy": "Yes",
       "Plan": "No"
  }
}
let obj2 = {
     "results": {
        "Action": "Failure!"
     },
     "report": {
         "Strategy": "Yep",
         "Plan": "Nope"
      }
 }
 
 let res = {
  results:{...obj1.results, ...obj2.results}, 
  report: {...obj1.report, ...obj2.report}
  };
 console.log(res)

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.