How to filter an object by the name of the property?

Asked

Viewed 47 times

-1

I have the following object:

obj = {
  "storySummaries": {
    "featuredStories": [],
    "trendingStories": [
      {
        "image": {
          "newsUrl": "...",
          "source": "...",
          "imgUrl": "..."
        },
        "entityNames": [
          "A",
          "B",
          "C"
        ]
      }, {
        "image": {
          "newsUrl": "...",
          "source": "...",
          "imgUrl": "..."
        },
        "entityNames": [
          "D",
          "E",
          "F"
        ]
      }
    ]
  },
  "date": "4 de mar de 2019",
  "hideAllImages": false
}

And I want to build an array with all fields of all entityNames. How do I get an array of type ["A", "B", "C", "D", "E", "F"]?

I tried the following code but found it very "ugly":

let hotTrendStories = JSON.parse(results)['storySummaries']['trendingStories'];
let entities = [];
hotTrendStories.forEach((story) => entities = entities.concat(story['entityNames']));

2 answers

2

You can use the function map that receives a function to iterate over the array, receiving as parameter the elements, just return the desired property, as this property is an array you need to concatenate

const list = [{
  "image": {
    "newsUrl": "...",
    "source": "...",
    "imgUrl": "..."
  },
  "entityNames": ["A", "B", "C"]
}, {
  "image": {
    "newsUrl": "...",
    "source": "...",
    "imgUrl": "..."
  },
  "entityNames": ["D", "E", "F"]
}];

let entityNames = list.map(item => item.entityNames);

console.log(entityNames);

entityNames = [].concat.apply([], entityNames);

console.log(entityNames);

  • Simple and clear solution. I really liked this interpreter in the answer. Where can I learn more about it?

  • I can’t say, take a look at the meta, but I use with the Ctrl + M. Only one observation, the answer side has a , which serves to accept the answer that best met your question, but also has one that serves to score positively, the first you must choose only one answer to give, already the second can give to all

1


a smaller second implementation is possible with Object.values()

var obj = {
    storySummaries: {
        featuredStories: [],
        trendingStories: [
            {
                image: {
                    newsUrl: '...',
                    source: '...',
                    imgUrl: '...',
                },
                entityNames: ['A', 'B', 'C'],
            },
            {
                image: {
                    newsUrl: '...',
                    source: '...',
                    imgUrl: '...',
                },
                entityNames: ['D', 'E', 'F'],
            },
            {
                image: {
                    newsUrl: '...',
                    source: '...',
                    imgUrl: '...',
                },
                entityNames: ['G', 'H', 'I'],
            },
        ],
    },
    date: '4 de mar de 2019',
    hideAllImages: false,
}
const entityNames = Array.concat.apply([],Object.values(obj)[0].trendingStories.map(item => item.entityNames))
  • To my mind that Object.values it just gets in the way, increases the amount of code and makes it more complex, I don’t see any reason to use

  • I agree with the increase in complexity, but I don’t see how it can get in the way of Object.values() you have a code more readable and close to functional.

  • On the contrary Object.values returns an array with the object values, basically converts an object to array, then Object.values(obj)[0] is equal to obj.storySummaries but the second is much more readable and simple, and does not depend on the order of the properties

Browser other questions tagged

You are not signed in. Login or sign up in order to post.