0

This is my original Object:

Data = {
  aesthetic: {
    heritage: 'aesthetic',
    description: 'sdokjosk',
    value: 5
  },
  architectural: {
    heritage: 'architectural',
    description: 'doodsjdj',
    value: 1
  },
  historical: {
    heritage: 'historical',
    description: 'dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ',
    value: 4
  },
  score: 3
};

i want to write a function that goes through the object and converts the properties only with 'heritage' 'description' and 'value' into an array that would look like this:

 [{
    "heritage": "aesthetic",
    "description": "sdokjosk",
    "value": 5
 },
  {
    "heritage": "architectural",
    "description": "doodsjdj",
    "value": 1
  },
  {
    "heritage": "historical",
    "description": "dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ",
    "value": 4
  }
]

This is what I have tried:

Object.values(Data) but this returns an array with the 3 from the score property at the end

5
  • Do you want object with 3 properties specified or do you just want to rule out value key from consideration? Commented Jul 13, 2018 at 11:47
  • "i want to write a function" - what's stopping you? Commented Jul 13, 2018 at 11:47
  • Post your own effort. Commented Jul 13, 2018 at 11:48
  • @vibhor1997a i have. Commented Jul 13, 2018 at 11:52
  • @NikhilAggarwal no there will be more than 3 properties the main thing is getting rid of the score property Commented Jul 13, 2018 at 11:53

2 Answers 2

2

You can use Object.values() method to get the array of values, then filter only objects from it using Array#filter() method.

This is how should be your code:

var result = Object.values(Data).filter(x => typeof x == 'object');

Demo:

This is a working demo snippet:

var Data = {
  aesthetic: {
    heritage: 'aesthetic',
    description: 'sdokjosk',
    value: 5
  },
  architectural: {
    heritage: 'architectural',
    description: 'doodsjdj',
    value: 1
  },
  historical: {
    heritage: 'historical',
    description: 'dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ',
    value: 4
  },
  score: 3
};

var result = Object.values(Data).filter(x => typeof x == 'object');
console.log(result);

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

Comments

1

If you want to check all the keys you mentioned should present you can go with this :

Object.values(Data).filter(function(data){return data["heritage"] && data["description"] && data["value"]})

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.