简体   繁体   English

Object.keys(object).map()不返回键

[英]Object.keys(object).map() does not return the keys

I am creating an Ionic project. 我正在创建一个离子项目。

I have a node "menu" from firebase like this: 我有一个来自firebase的节点"menu" ,如下所示:

"menu" : {
    "fhsSuizYVhYfwk3jE6Hs1jJ9mul2" : {
      "-LPgLdhiRWtzGZcT68kB" : {
        "category" : "Chicken",
        "menuContent" : {
          "-LPjfZG88i8oir4qZeUr" : {
            "description" : "Tasty & Spicy",
            "menuName" : "Chicken Spicy",
            "menuPrice" : "15000"
          },
          "-LPjmsYuscg0ceMTMriM" : {
            "description" : "Delicious",
            "menuName" : "Sweet Chicken",
            "menuPrice" : "17000"
          }
        }
      },
      "-LPjoKAm8mQsNK1MAPsu" : {
        "category" : "Beef",
        "menuContent" : {
          "-LPk-5YZQtreZQw1vGyL" : {
            "description" : "Dark, sweet, spicy. Yumm!",
            "menuName" : "Beef Blackpepper",
            "menuPrice" : "20000"
          }
        }
      },
      "-LPkyRkZPXMQjXdzoWfA" : {
        "category" : "Sayur",
        "menuContent" : {
          "-LPl68GYGz1K966w5Aci" : {
            "description" : "bayam enak tumis ikan asin",
            "menuName" : "Bayam ikan asin",
            "menuPrice" : "15000"
          }
        }
      },
      "-LPlOQO3it27qTQ3sjXl" : {
        "category" : "nasi",
        "menuContent" : {
          "-LPlOUF_F44RiQZPr45k" : {
            "description" : "enak",
            "menuName" : "nasgor",
            "menuPrice" : "9000"
          }
        }
      },
      "-LPq2Rxx-J3Vi2tkTnXC" : {
        "category" : "Minuman"
      },
      "-LPq2UQ3QDzaZuZAAC7n" : {
        "category" : "Dessert"
      },
      "-LPq2Wua9lDJBJpmY4qB" : {
        "category" : "Appetizer"
      }
    }
  }

I want to get the keys and values from that node and store it in a local variable menuCatLocalArr . 我想从该节点获取键和值,并将其存储在本地变量menuCatLocalArr This is my code order-menu.ts : 这是我的代码order-menu.ts

export class OrderMenuPage {

  public categories: string;
  public menuCatLocalArr = [];
  private currentNumber = 0;

  menuCatRef: AngularFireList<MenuCategory>;
  menuCatData: Observable<AngularFireAction<DatabaseSnapshot<MenuCategory>>[]>;

  restoData: {key: string}; //this parameter is passed from HomePage

  public menuOrder : MenuOrder[] = [];
  public showButton: boolean = true;

  constructor(private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase,
    private toast: ToastController,
    public navCtrl: NavController, public navParams: NavParams) {
      this.restoData = navParams.get('restoDataPass');
  }

  ionViewDidLoad() {
    this.afAuth.authState.subscribe(data => {
      if(data && data.email && data.uid){

        this.menuCatRef = this.afDatabase.list<MenuCategory>(`menu/${this.restoData.key}`);
        this.menuCatData = this.menuCatRef.snapshotChanges();
        this.menuCatData.subscribe(result => {
          this.categories = result[0].payload.val().category; // assign the first category to segment
          for (let i=0; i<result.length; i++){
            if(result[i].payload.val().menuContent){
              let dataArray = {
                key: result[i].payload.key,
                category: result[i].payload.val().category,
                menuContent: Object.keys(result[i].payload.val().menuContent).map(x =>
                  result[i].payload.val().menuContent[x]
                ),
              }
              this.menuCatLocalArr.push(dataArray);
            }
            else{
              let dataArray = {
                key: result[i].payload.key,
                category: result[i].payload.val().category,
                menuContent: ''
              }
              this.menuCatLocalArr.push(dataArray);
            }
            console.log(Object.keys(result[i].payload.val().menuContent));
          }
          console.log("menuCatLocalArr: ");
          console.log(this.menuCatLocalArr);
        });
        console.log("menuCatData: ");
        console.log(this.menuCatData);

      }
      else {
      }
    });
  }
}

When I console.log(this.menuCatLocalArr) , under menuContent I get this this: I console.log(this.menuCatLocalArr) ,在menuContent下,我得到这个:

[
  {
    "0": {
      "description": "Tasty & Spicy",
      "menuName": "Chicken Spicy",
      "menuPrice": "15000"
    },
    "1": {
      "description": "Delicious",
      "menuName": "Sweet Chicken",
      "menuPrice": "17000"
    }
  }
]

Notice that the key ( -LPjfZG88i8oir4qZeUr , -LPjmsYuscg0ceMTMriM ) is now an index 0 , 1 . 请注意,密钥( -LPjfZG88i8oir4qZeUr-LPjmsYuscg0ceMTMriM )现在是一个索引01

What should I do if I want to get this instead: 如果我想得到这个怎么办:

[
  {
    "0": {
      "keys": "-LPjfZG88i8oir4qZeUr",
      "description": "Tasty & Spicy",
      "menuName": "Chicken Spicy",
      "menuPrice": "15000"
    },
    "1": {
      "keys": "-LPjmsYuscg0ceMTMriM",
      "description": "Delicious",
      "menuName": "Sweet Chicken",
      "menuPrice": "17000"
    }
  }
]

Thanks for helping. 感谢您的帮助。

You can get both the keys and values with Object.entries() . 您可以使用Object.entries()获得键和值。

Now your question has an input that really is an array having one object. 现在,您的问题的输入实际上就是一个具有一个对象的数组。 I suppose you know how to access the object in that array (like array[0] ), and so the question really is how to deal with that object. 我想您知道如何访问该数组中的对象(例如array[0] ),因此问题实际上是如何处理该对象。 I will ignore the array wrapper which seems unrelated to your question. 我将忽略似乎与您的问题无关的数组包装器。

Secondly, your desired output is also a bit overkill: the inner object has numerical keys, which is really what arrays provide, so it seems to me you don't really need to wrap such an object in an array: just make it an array. 其次,您所需的输出也有点过大:内部对象具有数字键,这确实是数组提供的功能,因此在我看来,您并不需要将此类对象包装在数组中:只需将其包装成数组即可。

Here is how you can do the basic operation with ES6 code: 这是使用ES6代码进行基本操作的方式:

 const obj = { "-LPjfZG88i8oir4qZeUr": { "description": "Tasty & Spicy", "menuName": "Chicken Spicy", "menuPrice": "15000" }, "-LPjmsYuscg0ceMTMriM": { "description": "Delicious", "menuName": "Sweet Chicken", "menuPrice": "17000" } }; const result = Object.entries(obj).map(([key, value]) => ({key, ...value})); console.log(result); 

The above code uses several ES6 features which may not be available in your environment: Object.entries and spread syntax for object literals are not always supported. 上面的代码使用了几种ES6功能,这些功能在您的环境中可能不可用:不总是支持Object.entries和对象常量的传播语法。

Here is code that poses fewer ES6-compliancy requirements: 这是对ES6兼容性要求较少的代码:

 const obj = { "-LPjfZG88i8oir4qZeUr": { "description": "Tasty & Spicy", "menuName": "Chicken Spicy", "menuPrice": "15000" }, "-LPjmsYuscg0ceMTMriM": { "description": "Delicious", "menuName": "Sweet Chicken", "menuPrice": "17000" } }; const result = Object.keys(obj).map(key => Object.assign({key: key}, obj[key])); console.log(result); 

You can iterate over the array using forEach and obtain keys and values for each object. 您可以使用forEach遍历数组,并获取每个对象的键和值。

let data = [
  {
    "-LPjfZG88i8oir4qZeUr": {
      "description": "Tasty & Spicy",
      "menuName": "Chicken Spicy",
      "menuPrice": "15000"
    },
    "-LPjmsYuscg0ceMTMriM": {
      "description": "Delicious",
      "menuName": "Sweet Chicken",
      "menuPrice": "17000"
    }
  }
]

data.forEach((obj)=>{ 
  Object.keys(obj).forEach((key,index)=>{
    console.log('key:'key,'value:',obj[key]);
  })     
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM