0

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.

1

2 Answers 2

2

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

I tried to use without Object.values, it says 'Cannot convert undefined or null to object'
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
0

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);

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.