1

I have an array of objects like below;

const arr1 = [
  {"name": "System.Level" },
  {"name": "System.Status" },
  {"name": "System.Status:*" },
  {"name": "System.Status:Rejected" },
  {"name": "System.Status:Updated" }
]

I am trying to split name property and create an object. At the end I would like to create an object like;

{
  "System.Level": true,
  "System.Status": {
    "*": true,
    "Rejected": true,
    "Updated": true
  }
}

What I have done so far;

transform(element){
  const transformed = element.split(/:/).reduce((previousValue, currentValue) => {
    previousValue[currentValue] = true;
  }, {});
  console.log(transofrmed);
 }

const transofrmed = arr1.foreEach(element => this.transform(element));

The output is;

{System.Level: true}
{System.Status: true} 
{System.Status: true, *: true}
{System.Status: true, Rejected: true}
{System.Status: true, Updated: true}

It is close what I want to do but I should merge and give a key. How can I give first value as key in reduce method? Is it possible to merge objects have same key?

2
  • do you have more than two levels? Commented Sep 30, 2018 at 15:16
  • @NinaScholz actually no, it will always be one or two Commented Sep 30, 2018 at 15:19

2 Answers 2

1

You could reduce the splitted keys adn check if the last level is reached, then assign true, otherwise take an existent object or a new one.

const
    array = [{ name: "System.Level" }, { name: "System.Status" }, { name: "System.Status:*" }, { name: "System.Status:Rejected" }, { name: "System.Status:Updated" }],
    object = array.reduce((r, { name }) => {
        var path = name.split(':');
            last = path.pop();
        path.reduce((o, k) => o[k] = typeof o[k] === 'object' ? o[k] : {}, r)[last] = true;
        return r;
    }, {});
    
console.log(object);

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

1 Comment

Thanks @NinaScholz
1

Use Array.reduce() on the list of properties. After splitting the path by :, check if there is second part. If there is a second part assign an object. Use object spread on the previous values, because undefined or true values would be ignored, while object properties would be added. If there isn't a second part, assign true as value:

const array = [{ name: "System.Level" }, { name: "System.Status" }, { name: "System.Status:*" }, { name: "System.Status:Rejected" }, { name: "System.Status:Updated" }];

const createObject = (arr) => 
  arr.reduce((r, { name }) => {
    const [first, second] = name.split(':');
    
    r[first] = second ? { ...r[first], [second]: true } : true;
    
    return r;
  }, {});
    
console.log(createObject(array));

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.