Search code examples
javascriptarraysobjectsplice

Object.keys, slice and splice


So I am still learning arrays and objects, and I'm a little bit stuck. I made an example of array of objects:

var something = {candy:[{name:"snickers", price:2},
                    {name:"bounty", price:3},
                    {name:"mars", price:4}]};

Object.keys(something.candy).filter(function(obj){
return console.log(something.candy[obj].name);
})

1. Question - Why doesn't it work when I write.:

var candy1 = Object.keys(something.candy);
candy1.filter(function(obj){
return console.log(obj.name);
});

Isn't it practically the same code meaning as above?

2.Question How come slice works and splice doesn't???

Object.keys(something.candy).filter(function(obj){
return console.log(something.candy[obj].name.slice(0,3));
})

Object.keys(something.candy).filter(function(obj){
return a(something.candy[obj].name.splice(1,3));
})

Solution

  • It's helpful to pull each piece apart and look at it when learning this. For example you have an object:

    var something = {candy:[{name:"snickers", price:2},
                    {name:"bounty", price:3},
                    {name:"mars", price:4}]};
    
    // what is something.candy:
    
    console.log("candy:", something.candy)
    
    // an array -- so what do you get with Object.keys?
    
    var candy1 = Object.keys(something.candy)
    console.log("keys:", candy1)
    
    // just the indexes!
    
    // So when you try to filter
    candy1.filter(function(obj){
        // there is no obj.name becuase each object is just a number
        return console.log(obj);
    });

    I think you want to just do this:

    var something = {candy:[{name:"snickers", price:2},
                        {name:"bounty", price:3},
                        {name:"mars", price:4}]};
    
    var select = something.candy.filter(obj => {
      console.log(obj.name) // look at them all
      return obj.name === "mars" // just pick this one
    })
    
    console.log("filtered: ", select)