-1

How to do a remapo for new objects like:

...
const inputArr = [
{id: '1', name: "test1", routeName: "somethig/something"},
{id: '2', name: "something2", routeName: "foo/bar"},
{id: '3', name: "someanothrelement", routeName: "test/test"}
]

//to => 

const resultStructureArr = [
  { id: '1', value: 'somethig/something', label: 'test1' },
  { id: '2', value: 'foo/bar', label: 'something2' },
  { id: '3', value: 'test/test', label: 'someanothrelement' },
];
...

Here is the jsfiddle

pilchard
  • 12,414
  • 5
  • 11
  • 23
Stefan89BEG
  • 129
  • 2
  • 4
  • 17

2 Answers2

1

Just using map() can do it

const inputArr = [
{id: '1', name: "test1", routeName: "somethig/something"},
{id: '2', name: "something2", routeName: "foo/bar"},
{id: '3', name: "someanothrelement", routeName: "test/test"}
]

let result = inputArr.map(a => ({'id':a.id,'label':a.name,'value':a.routeName}))

console.log(result)
flyingfox
  • 13,414
  • 3
  • 24
  • 39
-1

We can use traditional for loop for this. Where we may loop to the length of list and for each iteration we may add new object into result array using Array.prototype.push method. Secondly we are doing the same thing with foreach loop. Third I'm using Array.prototype.map method, Which creates a new result for each iteration, in our case we are returning our new object. Lastly we are using Array.prototype.reduce method, with this method we can initialize a starting value which in my case I'm using empty array, then for each iteration I'm pushing a new object in that array and returning it.

const inputArr = [
  { id: "1", name: "test1", routeName: "somethig/something" },
  { id: "2", name: "something2", routeName: "foo/bar" },
  { id: "3", name: "someanothrelement", routeName: "test/test" },
];

// Using for loop
let result = [];
for (let i = 0; i < inputArr.length; i++) {
  result.push({
    id: inputArr[i].id,
    value: inputArr[i].routeName,
    label: inputArr[i].name,
  });
}

console.log(result);

result = [];
// using foreach loop
inputArr.forEach((item) => {
  result.push({ id: item.id, label: item.name, value: item.routeName });
});

console.log(result);

result = [];
// using map
result = inputArr.map((item) => ({
  id: item.id,
  label: item.name,
  value: item.routeName,
}));

console.log(result);
result = [];
// using reduce
result = inputArr.reduce((acc, curr) => {
  acc.push({ id: curr.id, label: curr.name, value: curr.routeName });
  return acc;
}, []);
console.log(result);