1

I would like to get values from object and save it into array...This is how my object is structured.

0: {name: "John Deo", age: 45, gender: "male"}
1: {name: "Mary Jeo", age: 54, gender: "female"}
2: {name: "Saly Meo", age: 55, gender: "female"}

But I am looking for something like this.

0: ["John Deo", 45, "male"]
1: ["Mary Jeo", 54, "female"]
2: ["Saly Meo", 55, "female"]

This is where I got stuck.

for(let i in data){
   _.map(data[i], value =>{
        console.log(value)
    })
}

3 Answers 3

3

You can use the function Array.prototype.map to iterate over your data and run the function Object.values on each object to extract its values as an array.

const data = [
  {name: "John Deo", age: 45, gender: "male"},
  {name: "Mary Jeo", age: 54, gender: "female"},
  {name: "Saly Meo", age: 55, gender: "female"}
];
result = data.map(Object.values);
    
console.log(result);

Note that iterating over properties of an object this way might return then in an arbitrary order so if you need to ensure the order you should use a custom function to extract the values (this is especially easy using ES6 destructuring):

const data = [
  {name: "John Deo", age: 45, gender: "male"},
  {name: "Mary Jeo", age: 54, gender: "female"},
  {name: "Saly Meo", age: 55, gender: "female"}
];
const extractValues = ({name, age, gender}) => [name, age, gender];
result = data.map(extractValues);
        
console.log(result);

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

1 Comment

THANKS! you don't know how long that took me. it is working now.
0

Try this:

data.map(obj => Object.values(obj))

Comments

0

Another option would be to use the Object.values() method.

var obj = {name: "John Deo", age: 45, gender: "male"}; 

console.log(Object.values(obj));

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.