0

I currently have an array of objects which is the following.

[
  { desc: '1', qty: '2', amt: '1', index: 0 },
  { desc: '1', qty: '2', amt: '1', index: 1 }
]

I need to turn this array of objects to something like that

[
     ['1','2','1',0 ],
     ['1','2','1',1]
]

Any ideas?

1
  • 1
    The desired output has no valid syntax. Instead of {} you can have [] for each elements. Commented Sep 20, 2020 at 15:22

3 Answers 3

2

If the order of the properties in the object is guaranteed, you can use create a new array with Array.map(), and use Object.values() as the callback:

const arr = [
  { desc: '1', qty: '2', amt: '1', index: 0 },
  { desc: '1', qty: '2', amt: '1', index: 1 }
]

const result = arr.map(Object.values)

console.log(result)

If the order of the properties in the objects might change, use Array.map(), and then call Array.map() again to extract the properties that you want in the the order you specify:

const arr = [
  { desc: '1', qty: '2', amt: '1', index: 0 },
  { desc: '1', qty: '2', amt: '1', index: 1 }
]

const order = ['desc', 'qty', 'amt']; // 'index' removed

const result = arr.map(o => order.map(k => o[k]))

console.log(result)

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

7 Comments

i want to ask you if i want to ignore one element like i dont want "index" in my new array is it possible?
If you use the 2nd method (the order array), you can decide which properties to include. See updated example.
thank you!! can i ask you one more question? sorry for bothering
Sure. As long as it's related to the current question/answer.
yes it is, i need to add a separate value to my new array (the one we got after the mapping). how can i add that value i have it saved as a let
|
2

You can use .map() and Object.values():

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.)

Try as the following:

const data = [
  { desc: '1', qty: '2', amt: '1', index: 0 },
  { desc: '1', qty: '2', amt: '1', index: 1 }
]

const result = data.map(e => Object.values(e))

console.log(result)

Comments

1
const data = [
  { desc: '1', qty: '2', amt: '1', index: 0 },
  { desc: '1', qty: '2', amt: '1', index: 1 }
];

var arr = [];

data.map(function(obj) {
   arr.push(Object.values(obj))
});

console.log(arr) // value gets stored in arr object

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.