【问题标题】:Return object has condition true from object has key从对象有键返回对象的条件为真
【发布时间】:2020-04-28 21:28:10
【问题描述】:

我对对象有疑问。我想filter 返回键列表在下面的这个对象中条件为真:

myObject = {
   key1: {
     name:"key1",
     select:true
   },
   key2: {
     name:"key2",
     select:false
   },
   key3: {
     name:"key3",
     select:true
   }
}

出于某种原因,我必须为其添加特定的密钥。现在我想返回一个数组有 seclect true

arrayWantreturn = ["key1", "key3"]

非常感谢您的帮助。

【问题讨论】:

    标签: javascript arrays object ecmascript-6 filter


    【解决方案1】:

    你可以用那个对象做一个循环:

    var myObject = {
       key1: {
         name:"key1",
         select:true
       },
       key2: {
         name:"key2",
         select:false
       },
       key3: {
         name:"key3",
         select:true
       }
    };
    
    var arr = [];
    
    for (var prop in myObject) {
        if (myObject[prop].select) {
            arr.push(myObject[prop].name);
        }
    }
    
    console.log(arr);

    【讨论】:

      【解决方案2】:

      也许您可以尝试以下方法:

      const myObject = {
         key1: {
           name:"key1",
           select:true
         },
         key2: {
           name:"key2",
           select:false
         },
         key3: {
           name:"key3",
           select:true
         }
      };
      
      const result = Object.entries(myObject)
                           .filter(([k, v]) => v['select'])
                           .flatMap(e => e[1].name);
      
      console.log(result);

      希望对你有帮助!

      【讨论】:

        【解决方案3】:

        您可以使用Object.values() 获取对象的值,然后使用.filter() 保留所有具有selecttrue 的对象。然后,您可以将每个剩余的对象 .map() 设置为它的 name 属性,如下所示:

        const myObject = { key1: { name:"key1", select:true }, key2: { name:"key2", select:false }, key3: { name:"key3", select:true } };
        const res = Object.values(myObject)
                      .filter(({select}) => select)
                      .map(({name}) => name); 
              
        console.log(res);

        这使用destructuring assignment 提取回调方法参数中的属性值。

        【讨论】:

          猜你喜欢
          • 2015-11-15
          • 1970-01-01
          • 2016-05-03
          • 1970-01-01
          • 2019-07-01
          • 2017-11-16
          • 2018-10-18
          • 2019-04-29
          • 2016-01-03
          相关资源
          最近更新 更多