代码之家  ›  专栏  ›  技术社区  ›  Eleven11

对象键、切片和拼接

  •  5
  • Eleven11  · 技术社区  · 7 年前

    所以我还在学习数组和对象,我有点卡住了。 我举了一个对象数组的例子:

    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.问题-为什么我写作时它不起作用:

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

    2.问题:为什么切片工作而拼接不工作???

    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));
    })
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Mark    7 年前

    在学习这一点的时候,把每一部分都分开来看是很有帮助的。例如,您有一个对象:

    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);
    });

    我想你只需要这样做:

    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)