0

I have an Array var category:

var category = ["all", "Items Id", "Items Sku", "Items Name"]

I need to convert it to a JSON object in the following format:

var category = [{
  "id": "all",
  "text": "all",
  "children": [{
    "id": "Items Id",
    "text": "Item Id"
  }, {
    "id": "Items Sku",
    "text": "Items Sku"
  }, {
    "id": "Items Name",
    "text": "Items Name"
  }]
}, ];

I'm trying to work with the code below but doesn't work:

var category = ["all", "Items Id", "Items Sku", "Items Name"]

var json = header.map((str, index) => ({ text: str, id: index + 1 }));

var categorylist = [];

for (var i in json) {
  categories.push({
    "id": json[0].value,
    "text": json[0].value,
    "children": [{
      id: json[i].value,
      text: json[i].value
    }]
  }

  console.log(categorylist)

Any help?

3

2 Answers 2

1

map() for the children using a bit of destructuring to separate the first element from the rest of array

const category = ["all", "Items Id", "Items Sku", "Items Name"],
      getObj = ([id,...rest]) => ({id,text:id, children: rest.map(id => ({id, text:id}))}),      
      res = [getObj(category)];

console.log(res)

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

Comments

1

You can use array#map to generate children skipping the first item and then generate your array by adding id and text for the first item and adding the children.

const category = ["all", "Items Id", "Items Sku", "Items Name"],
      children = category.slice(1).map(id => ({id, text: id})),
      result = [{id: category[0], text: category[0], children}];
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.