-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

1

2 Answers 2

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)

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

7 Comments

You have enough rep to know that a question like this is undoubtedly a duplicate. vote to close.
@pilchard,You are right,but I am just want to make my reputation over 10000,thanks
That is the worst reason to answer duplicates.
@pilchard Ok,I got it and will avoid it,thanks again
by 'avoid it' you mean you will flag this question as duplicate and delete your answer?
|
-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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.