0

Hello Everyone I'm beginner in javascript I'm trying to convert from Array of objects into Array of array.I have tried some methods like Object.entries.But I didn't get the output what I expected.If anyone helps It will really helpful to me.Any kind of help would be appreciated.Thanks in advance....

My Input:

  var data=[
           {name:'TOYA',price:34},
           {name:'TOYB',price:24},
           {name:'TOYC',price:444},
           {name:'TOYD',price:54}
        ];


Expected Output:

   var data=[
           ['TOYA',34],
           ['TOYB',24],
           ['TOYC',444],
           ['TOYD',54]
        ];
     
 But I got:
 
[ [ '0', { name: 'TOYA', price: 34 } ],
  [ '1', { name: 'TOYB', price: 24 } ],
  [ '2', { name: 'TOYC', price: 444 } ],
  [ '3', { name: 'TOYD', price: 54 } ] ]
  
 using Object.entries(data);

4
  • 4
    [name:'c++',price:34] not valid javascript, so you can't get that with any code Commented Mar 28, 2020 at 8:17
  • Would I be right in assuming that you mean [["name", "c++"], ["price", 34]] Commented Mar 28, 2020 at 8:23
  • so, what you want is an Array of Array ... not an Array of Array of Array Commented Mar 28, 2020 at 8:26
  • You need to use Object.values, see my answer. Commented Mar 28, 2020 at 8:34

3 Answers 3

1

Use Object.values instead.

var data=[
     {name:'TOYA',price:34},
     {name:'TOYB',price:24},
     {name:'TOYC',price:444},
     {name:'TOYD',price:54}
];

var newdata = [];
for (let obj of data) {
  newdata.push(Object.values(obj));
}
console.log(newdata)

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

1 Comment

@LearnforFun - I see you found out the problem
0

var data=[
           {name:'c++',price:34},
           {name:'java',price:24},
           {name:'python',price:444},
           {name:'php',price:54}
        ];


var result = Object.values(data).map(v => Object.values(v));
console.log(result)

2 Comments

Extremely Sorry for your inconvenience.I have changed my expected output.
@VigneshRaviKumar - the code now works as you require
0

You can use Object.values(arrayElement)

[{name:'c++',price:34},{name:'java',price:24},{name:'python',price:444},       {name:'php',price:54}].map((e)=>{return [Object.values(e)]})

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.