Grijan
Grijan

Reputation: 298

Trying to iterate through list of objects in node js

I'd like to send list of objects through postman tool and receive it on my server side code, This is the json code i'm sending through postman tool and receiving it throught post method

{
    "user1" : {
        "name" : "grijan",
        "prof" : "student"
    },
    "user2" : {
        "name" : "vijay",
        "prof" : "teacher"
    }
}

My server side code

var express = require('express');
var app = express();


app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/saveUser',function(req,res){
    var  obj= req.body;
    console.log(obj);
    //code for iteration ????
})

var server = app.listen(8008,function(){});

I need to iterate through the objects and the fields in the objects! FYI i'm new to node this is my 2nd day :)

Upvotes: 2

Views: 3285

Answers (2)

Sharoon Ck
Sharoon Ck

Reputation: 788

Anyone who is looking for the latest and Built-in solution. We can use Object.entries() method which is introduced in ES7

const obj = { a: 5, b: 7, c: 9 };

for (const [key, value] of Object.entries(obj)) {
  
  //you can do your operations here
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"

}

you can find additional features and examples of Object.entries here enter link description here

Upvotes: 1

David Vicente
David Vicente

Reputation: 3131

You are not sending a list, but an object. If you want to send a list you should send something like this:

[
    {
        "name" : "grijan",
        "prof" : "student"
    },
    {
        "name" : "vijay",
        "prof" : "teacher"
    }
]

And them in the node side:

var express = require('express');
var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

var methodToSaveInDB = function(name, prof) {
    // save it here into DB
}

app.post('/saveUser',function(req,res){
    var usersList = req.body;
    for(var user of usersList) {
        methodToSaveInDB(user.name, user.prof);
    }
})

var server = app.listen(8008,function(){});

If you need to send it like an object and not as a list, you could loop through object properties:

for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
        console.log(obj[property].name);
        console.log(obj[property].prof);
    }
}

Upvotes: 2

Related Questions