1

I have a rest API in Node.js, which outputs an array like:

[["Benni", 24, "Whatever"], ["Paul", 23, "Whatever"]]

Now in order to use it for an Angular Material table, I have to put the array in this format:

[{name: 'Benni', age: 24, Text: 'Whatever'}, {name: 'Paul', age: 23, Text: 'Whatever'},] 

How can I achieve that?

3 Answers 3

3

You can use the Array.prototype.map method of an array.

Simply call a map over the array, get the data in order from the array item and return the object you want in the map function.

const arr = [
  ["Benni", 24, "Whatever"],
  ["Paul", 23, "Whatever"]
];

const remapped = arr.map((data) => {
  const [name, age, Text] = data;
  return {
    name,
    age,
    Text,
  };
});

console.log(remapped);

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

Comments

1

pretty easily:

let result = inputArr.map( innerArr => {name: innerArr[0], age: innerArr[1], Text: innerArr[2]});

Comments

0

you can do it as follows,

var data = [[ "Benni" , 24 , "Whatever" ],[ "Paul" , 23 , "Whatever" ]];

var collection = data.slice(); // make a copy
var keys = ["name","age","text"];

collection = collection.map(function (e) {
    var obj = {};

    keys.forEach(function (key, i) {
        obj[key] = e[i];
    });

    return obj;
});

collection object will contain the results as follows

    [
  {
    "name": "Benni",
    "age": 24,
    "text": "Whatever"
  },
  {
    "name": "Paul",
    "age": 23,
    "text": "Whatever"
  }
]

See this for full code : JSFiddle

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.