0

I have a JSON Data that I am getting from URL. I want to merge the data which has same Value Below is the sample data. I have searched through the Internet,but i didn't got the solution. All i found is for same Keys.

  [ {
    "banana": [
      {
        "color": yellow,
        "size": "small"
      },
      {
        "size": "medium"
      },
      {
        "size": "large"
      }
    ],
    "process_name": "fruits"},{
    "carnivores": [
      {
        "name": "lion"
      },
      {
        "name": "tiger"
      },
      {
        "name": "chetah"
      },
      {
        "name": "dianosaur"
      }
    ],
    "process_name": "animal"}, {
    "apple": [
      {
        "color": red,
        "size": "large"
      }
    ],
    "process_name": "fruits"}]

And I want to merge the data of "process_name" :"fruits" into one array as below and the result should be

[{
"banana": [
  {
    "color": yellow,
    "size": "small"
  },
  {
    "size": "medium"
  },
  {
    "size": "large"
  }
],
"apple": [
  {
    "color": red,
    "size": "large"
  }
],
"process_name": "fruits"  }, {
"carnivores": [
  {
    "name": "lion"
  },
  {
    "name": "tiger"
  },
  {
    "name": "chetah"
  },
  {
    "name": "dianosaur"
  }
],
"process_name": "animal"}]

can anyone help on this?

0

1 Answer 1

2

Just some snippet to start:

// data definition
const json_before = [ {
  "banana": [
    {
      "color": "yellow",
      "size": "small"
    },
    {
      "size": "medium"
    },
    {
      "size": "large"
    }
  ],
  "process_name": "fruits"},
{
  "carnivores": [
    {
      "name": "lion"
    },
    {
      "name": "tiger"
    },
    {
      "name": "chetah"
    },
    {
      "name": "dianosaur"
    }
  ],
  "process_name": "animal"},
{
  "apple": [
    {
      "color": "red",
      "size": "large"
    }
  ],
  "process_name": "fruits"
}];

// processing
const json_after = json_before.reduce((arr, next) => {
  const exist = arr.find(el => el.process_name === next.process_name);
  if (exist) Object.assign(exist, next);
  else arr.push(next);
  return arr;
}, []);

// check
console.log(json_after);

The main idea is to use reduce for array traversing. To shorten the processing code, I've used Object.assign to modify previuosly added element, although in real code it's better to use Object.keys and manually check whether the properties of the previous object aren't overwritten.

Note that this is mutating the source data (check by adding console.log(json_before)). Again, if you don't want this, you should clone each element yourself, without direct object assignment.

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

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.