0

I have a Json data

   var orign = {
            users: [
                { name: "name1", id: "aaa1", classify: "depth1" },
                { name: "name2", id: "aaa2", classify: "depth1" },
                { name: "name3", id: "aaa3", classify: "depth2" },
            ]
        }

I want to change json data like this

        var result = {
            "depth1" : [
                { name: "name1", id: "aaa1"},
                { name: "name2", id: "aaa2"},
            ],
            "depth2" : [
                { name: "name3", id: "aaa3"},
            ],
           
        }

how can I change this by Javascript?

2
  • 1
    Do you currently have any code, which you could provide? Commented Jan 5, 2021 at 12:42
  • 1
    Please be aware that var orign = { ... } is not JSON, it is a JavaScript object. Commented Jan 5, 2021 at 12:44

2 Answers 2

1

You can do the following using reduce,

origin = {
            users: [
                { name: "name1", id: "aaa1", classify: "depth1" },
                { name: "name2", id: "aaa2", classify: "depth1" },
                { name: "name3", id: "aaa3", classify: "depth2" },
            ]
        }

res = origin.users.reduce((prev, curr) => {
  const {classify, ...rest} = curr;
  if(prev.hasOwnProperty(classify)) {
    prev[classify].push(rest);
  } else {
    prev[classify] = [rest];
  }
  return prev;
}, {});

console.log(res);

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

Comments

0

This is quite similar question I posted a year ago here

Hope my answer could help

var origin = {
  users: [
      { name: "name1", id: "aaa1", classify: "depth1" },
      { name: "name2", id: "aaa2", classify: "depth1" },
      { name: "name3", id: "aaa3", classify: "depth2" },
  ]
};

const reducer = (acc, item) => {
  if (!acc[item.classify]) {
    acc[item.classify] = [];    
  } 
  acc[item.classify].push({name: item.name, id: item.id})
  
  return acc
}

const result = origin.users.reduce(reducer, {});

console.log(result)

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.