Home > Software design >  Foreach when key is not a number
Foreach when key is not a number

Time:07-06

In my project i push a array into a table in firebase realtime database. Firebase generate a token and not a numeric id for each array:

{
    "-N2mToYDj-i8ToErmaUj": {
        "anzahl": 2,
        "groesse": 0.5,
        "name": "getraenk1",
        "preis": 5.5
    },
    "-N2mX3RPnDXxWMHMJScy": {
        "anzahl": 1,
        "groesse": "0.25",
        "name": "getraenk2",
        "preis": 2.2
    },
    "-N2mXBT8c7EKlIgyrU72": {
        "anzahl": 1,
        "groesse": "0.5",
        "name": "getraenk3",
        "preis": 3.4
    },
    "-N2mXZD1BoCslj81Lcya": {
        "anzahl": 1,
        "groesse": "1",
        "name": "getraenk4",
        "preis": 5.2
    "-N2m_g8GutpAFqsN4WsP": {
        "anzahl": 1,
        "groesse": "0.33",
        "name": "getraenk5",
        "preis": 3.2
    },
}

How can i work with each object when the key value is not numeric. ForEach() does not work for me.

CodePudding user response:

If you just care about the values, wrap the result in Object.values. If you care about the keys also, wrap the result in Object.entries instead.

const data = {"-N2mToYDj-i8ToErmaUj":{"anzahl":2,"groesse":0.5,"name":"getraenk1","preis":5.5},"-N2mX3RPnDXxWMHMJScy":{"anzahl":1,"groesse":"0.25","name":"getraenk2","preis":2.2},"-N2mXBT8c7EKlIgyrU72":{"anzahl":1,"groesse":"0.5","name":"getraenk3","preis":3.4},"-N2mXZD1BoCslj81Lcya":{"anzahl":1,"groesse":"1","name":"getraenk4","preis":5.2},"-N2m_g8GutpAFqsN4WsP":{"anzahl":1,"groesse":"0.33","name":"getraenk5","preis":3.2}};

Object.values(data).forEach(value => console.log("value", value));

console.log("===================");
Object.entries(data).forEach(([key, value]) => console.log("key", key, "value", value));

CodePudding user response:

Looks like you're getting back an object not a list which is why forEach isn't working. You would need to loop through the keys of the returned object and pull the corresponding record that way.

You can do something like this to loop through the keys:

var object = {"one":"data-1","two":"data-2"}
var keys = Object.keys(object)
keys.forEach(function(key){
    console.log(key); 
    console.log(object[key])
})

CodePudding user response:

Lets say your data stored in test object. you can use Object function in javascript to work with any object. For accessing all key you can try this:

Object.keys(test).map(key => { // key in here can be for example -N2mToYDj-i8ToErmaUj
    const data = test[key] // this is the full object that each key points to
/* 
   {
        "anzahl": 2,
        "groesse": 0.5,
        "name": "getraenk1",
        "preis": 5.5
    }
*/
})
  • Related