In my angular app, I get the values from service as an array of objects like below.

temp=  [
    {
        "a": "AAA",
        "b": "bbbb",
        "c": "CCCC",
        "d": "ddddd",
    },
    {
        "a": "lmn",
        "b": "opq",
        "c": "rst",
        "d": "uvw",
    }
 ]

I need to format this temp to array of array of strings:

newTemp = 
[
 ['AAA', 'bbbb', 'CCCC', 'ddddd'],
 ['lmn', 'opq', 'rst', 'uvw'],
];

Should we need to do a forloop on each object or is there any straight forward way.

You can use Array.map

let newArray = arr.map(a => Object.values(a))

If you cant use Object.values

let newArray = arr.map(a => Object.keys(a).map(k => a[k]))

Output

(2) [Array(4), Array(4)]
    0:(4) ["AAA", "bbbb", "CCCC", "ddddd"]
    1:(4) ["lmn", "opq", "rst", "uvw"]
  • I tried to use without Object.values, it says 'Cannot convert undefined or null to object' – user1015388 2 days ago
  • @user1015388 - See this fiddle for an example: jsfiddle.net/0fgdcf3h – tymeJV 2 days ago
  • my bad, I was using a different variable. It works! – user1015388 2 days ago
  • one small simple change, is there a way that we add additonal elements to the new generated array. For example ['false', 1, "AAA", "bbbb", "CCCC", "ddddd"] Basically 'false' and a numeric to display rownumber – user1015388 2 days ago

Try the following :

temp=  [
    {
        "a": "AAA",
        "b": "bbbb",
        "c": "CCCC",
        "d": "ddddd",
    },
    {
        "a": "lmn",
        "b": "opq",
        "c": "rst",
        "d": "uvw",
    }
 ]
 
 var newTemp = [];
temp.forEach(function(obj){
    var arr = [];
   Object.keys(obj).forEach(function(key){
      arr.push(obj[key]);
   })
   newTemp.push(arr);
});
console.log(newTemp);

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.