How to change the format of an object in javascript?

Asked

Viewed 28 times

0

I have an object in the following format:

[
  {
    "path": "caminho1",
    "subpath": [ { "path": "1" }, { "path": "2" }, { "path": "3" }, { "path": "4" } ]
  },{
    "path": "caminho2",
    "subpath": []
  },{
    "path": "caminho3",
    "subpath": [ { "path": "1" }, { "path": "2" } ]
  },{
    "path": "caminho4",
    "subpath": [ { "path": "1" }, { "path": "2" }, { "path": "3" } ]
  }
]

and I want to turn to the following format:

[
  { params: { path: ["caminho1", "1"] } },
  { params: { path: ["caminho1", "2"] } },
  { params: { path: ["caminho1", "3"] } },
  { params: { path: ["caminho1", "4"] } },
  { params: { path: ["caminho3", "1"] } },
  { params: { path: ["caminho3", "2"] } },
  { params: { path: ["caminho4", "1"] } },
  { params: { path: ["caminho4", "2"] } },
  { params: { path: ["caminho4", "3"] } }
]

How do I make this change with Javascript? I know the function .reduce() can do this, but I can’t understand her right.

1 answer

2


Your object has two arrays, the object itself and then "subpath", so you need to interact on the two.

If you couldn’t understand reduce, maybe a forEach be simpler to understand:

var lista = [
  {
    "path": "caminho1",
    "subpath": [ { "path": "1" }, { "path": "2" }, { "path": "3" }, { "path": "4" } ]
  },{
    "path": "caminho2",
    "subpath": []
  },{
    "path": "caminho3",
    "subpath": [ { "path": "1" }, { "path": "2" } ]
  },{
    "path": "caminho4",
    "subpath": [ { "path": "1" }, { "path": "2" }, { "path": "3" } ]
  }
];

var novaLista = [];

lista.forEach(function (item) {
   item.subpath.forEach(function (subItem) {
    var pathItens = [];
    pathItens.push(item.path);
    pathItens.push(subItem.path);
    
    novaLista.push({ paramans: { path: pathItens }});
   });
});

console.log(novaLista);

Basically a new object (novaLista) was created to add the items of the new object that has a different format.

Has two iterations of forEach. In the second of the elements in "subpath" the object is created and added (push) the newList, I believe it’s simple to understand.

About function reduce, can read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

  • Thanks, son, I get it. I should correct myself in relation to reduce pq in this case of a path within a subpath I can’t make it appear the same, or it only appears as a string like "way1,1,way1,2..." or just as an array [Object Object]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.