0

Given following JSON object

var data = {
    "ok" : true,
    "messages" : [
        {
            "type" : "message",
            "subtype" : "bot_remove"
        },
        {
            "type":"message",
            "subtype":"file_share",
            "file" : {
                "name" : "file_name"
            },
        }    
    ],
    "has_more" : false
}

using jQuery I'de like to create a new JSON object that contains only the object with the value "file_share". Im just not sure if I should be using $.grep or javascript's delete

something like

var newObject = [];
var result = $.grep(data.messages , function(key,value){
    return +key.subtype !== "file_share";
    newObject.push(result)
}); 

or using $.grep to filter the object whose length more than 0 (as the second object contains a child object).

Would I then have to stringify and / or $.parseJSON() the newObject?

Ninita
  • 1,209
  • 2
  • 19
  • 45
James
  • 1,355
  • 3
  • 14
  • 38

2 Answers2

1

You should use Array.prototype.filter:

var result = data.messages.filter(function(obj) {
    return obj.subtype === 'file_share';
});

if (result.length) {
    // item found, use `result[0]` to access it
}
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Thanks for your time Alnitak, much appreciated. Can you explain if(result.length){} – James Jan 13 '16 at 18:03
  • The `if (result.length)` is there to ensure that the required object is actually found. You need `result[0]` but if the element doesn't exist the code would generate `undefined`. – Alnitak Jan 13 '16 at 18:07
  • Thanks. Im trying to access the file object. Something like $.each(result.file , function(){$('#ul').append('
  • '+this.name+'
  • ') }) ? – James Jan 13 '16 at 18:26
  • given only one matching object (your question strongly implied singular, not plural), there's no need for a `.each` - just use `result[0].file.name` – Alnitak Jan 13 '16 at 18:31
  • I think i did it but please check if you have a second: – James Jan 13 '16 at 18:32
  • var printList = $.each(result , function(i){ console.log(result[i].file.title) }) – James Jan 13 '16 at 18:33
  • `$.each` doesn't return a value, and your `file` sub-object doesn't contain a `title` key – Alnitak Jan 13 '16 at 18:39
  • Completely understand. I'd hoped to keep the amount of code I used to a minimum, but the api I'm using call in a number of objects with the same structure. Should I there fore use the $.each – it seems to work? Sorry for the obfuscation – James Jan 13 '16 at 18:47
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100613/discussion-between-james-and-alnitak). – James Jan 13 '16 at 18:49