-4

Given this array:

var a = [
  {
    "name": "Konji-fu",
    "bananas": [
      {
        "url": "//url1",
        "num": 16
      },
      {
        "url": "//url2",
        "num": 16
      }
    ]
  },
  {
    "name": "Salias",
    "bananas": [
      {
        "url": "//url4",
        "num": 16
      },
      {
        "url": "//url12",
        "num": 3
      }
    ]
  }
]

How can I check that it contains a bananas key?

Bonus question : How can I check for the presence of both a bananas key and an url key inside it?

EDIT :

var p = JSON.parse(a)

I tried testArray = 'feeds' in p, jQuery.inArray('feeds', p) and well, a lot of other stuff, see answers below. I just can't seem to check the keys in this particular array ; But feel free to downvote if you don't have the answer ;p

yPhil
  • 8,049
  • 4
  • 57
  • 83
  • [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) is meant to be used on a string. Your `a` variable is already a JavaScript array and does not need to be *parsed* – Phil Oct 25 '17 at 23:34
  • @Phil but if I don't do that, I can't use any array method: `TypeError: a.some is not a function` – yPhil Oct 25 '17 at 23:37
  • @Phil This snippet is the exact structure of my example. It's an array of values that I generate, and then [save to disk](https://developer.mozilla.org/en-US/docs/Web/API/Blob#Blob_constructor_example_usage), and to get proper values in the text file I have to JSON.stringify() the array. Then I get it back via a new [FileReader()](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) and it looks exactly like this in the console. – yPhil Oct 25 '17 at 23:43
  • Like I said, the code in your question must not match reality. If you were to take the `var a =...` code in your question and use `var p = JSON.parse(a)`, you would get an error like *"Unexpected token o in JSON at position 1"* – Phil Oct 25 '17 at 23:47

3 Answers3

2

How can I check that it contains a bananas key?

Assuming you mean

How can I check if any entry contains a bananas key

use Array.prototype.some()

// same object, just on one line
const a = [{"name":"Konji-fu","bananas":[{"url":"//url1","num":16},{"url":"//url2","num":16}]},{"name":"Salias","bananas":[{"url":"//url4","num":16},{"url":"//url12","num":3}]}]

let containsBananas = a.some(obj => 
    Object.prototype.hasOwnProperty.call(obj, 'bananas'))
    
console.info('Contains bananas:', containsBananas)

Bonus question : How can I check for the presence of both a bananas key and an url key inside it?

You can easily chain another Array.prototype.some() call inside the first one...

// same object, just on one line
const a = [{"name":"Konji-fu","bananas":[{"url":"//url1","num":16},{"url":"//url2","num":16}]},{"name":"Salias","bananas":[{"url":"//url4","num":16},{"url":"//url12","num":3}]}]

let containsBananasWithUrls = a.some(obj => 
    Array.isArray(obj.bananas) && obj.bananas.some(banana =>
        Object.prototype.hasOwnProperty.call(banana, 'url')
    )        
)

console.info('Contains bananas with URLs:', containsBananasWithUrls)

If you need to verify that every array element matches your criteria, you can easily substitute Array.prototype.some() for Array.prototype.every()

Phil
  • 157,677
  • 23
  • 242
  • 245
  • What is going on? This honestly doesn't work: `let b = p.some(obj => Object.prototype.hasOwnProperty.call(obj, 'bananas'))` of course, my array is a properly `JSON.parse(a)` object..? – yPhil Oct 25 '17 at 23:30
  • @yPhil what browser or environment are you using? It might not be compatible with the [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) though it would have to be pretty old – Phil Oct 25 '17 at 23:33
  • I'm using the latest Firefox, let me check... Yep, 65.0 - 64bits, on Ubuntu Linux – yPhil Oct 25 '17 at 23:34
  • @yPhil never mind, I think it's just a misunderstanding around `JSON.parse`. I've commented on your question – Phil Oct 25 '17 at 23:35
  • > // same object, just on one line: Phil, I think the problem is here. Probably the formatting of my string is not ok. It has been produced like this: `var json = JSON.stringify(data, null, 2),blob = new Blob([json], {type: "application/json"}),url = window.URL.createObjectURL(blob)` and, apparently, the formatting is not OK, although if it were really the case JSON.parse() my string would produce an error... – yPhil Oct 25 '17 at 23:49
  • @yPhil I literally copied the **code from your question** and removed the newlines / spaces. If your actual code is different, please update your question – Phil Oct 25 '17 at 23:50
  • it is different, I tried to explain 2 times in what way. Now when I load the file, and console.log() it, the snippet is what I see in the console. Yes, edited for clarity, dude, it's 30 pages long. I don't know how to make my question closer to my code, and believe me, I thought about it. – yPhil Oct 25 '17 at 23:52
  • Wait, it worked. p.some (the JSON.parsed string) works. Thanks. A lot. – yPhil Oct 26 '17 at 00:04
1

It looks like this question is already answered in another discussion. You may want to check this page: Checking if key exists in a JavaScript object

Edit: Someone in another discussion has proposed such a simple function:

    function lookup( arr, name ) {
    for(var i = 0, len = arr.length; i < len; i++) {
        if( arr[ i ].hasOwnProperty( name )
            return true;
    }
    return false;
}

You can check this discussion, if you like: Check if key exists in array object

kader
  • 24
  • 1
  • 4
  • This was posted as an answer, but it does not attempt to answer the question. It should possibly be an edit, a comment, another question, or deleted altogether. – Phil Oct 25 '17 at 22:57
  • Thank you for notifying. I am just new to StackOverflow, and do not have the privilege of commenting on questions. So, maybe I should delete this post. Sorry for any inconvenience. – kader Oct 25 '17 at 23:03
  • I figured. A moderator can convert your post into a comment. This is not a bad thing :) – Phil Oct 25 '17 at 23:04
  • ... And it does not work : `y.hasOwnProperty("feeds") => false` and yes, of course I knew about this post. But thank you for being positive. – yPhil Oct 25 '17 at 23:16
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/17738971) – t56k Oct 25 '17 at 23:32
  • @CD-RUM unless the link is to another StackOverflow post in which case, the voting system should be used – Phil Oct 25 '17 at 23:34
  • Thank you for notifying, I edited my answer. As I said, I am new to the StackOverflow, but I am a good learner so I will learn soon, hopefully :) Sorry for any inconvenience. – kader Oct 25 '17 at 23:48
0
let newArray = array.filter((item)=>{
    return item.bananas.filter(item2=>{
      return item2.url
    })
  })
LShapz
  • 1,738
  • 11
  • 19