简体   繁体   中英

How can I use all function arguments inside javascript Object.assign method

I am making a server using nodejs & express in which user can request some data and server send response. But, the data is array and I want to send a json response to the user. So, I used forEach() method of array and use Object.assign() , so that I can get object. But the problem is I cannot use 'index' argument of forEach() method while 'value' argument is properly getting used inside the callback function. When I use only 'index' argument, then my code runs ok but I want to use both arguments at the same time.

route.get('/getGPX/:number', passport.authenticate('jwt', { session: false }), (req, res) => {
    gpx.find({ username: req.user.username }, (err, result) => {
        if (err) console.log(err);
        if (result) {
            if (result.length === 0) {
                res.end();
                console.log('ended')
            }
            else {
                var jsonRes = {};
                result.forEach((value, index) => {

I can use 'value' but not 'index' from the arguments

                    jsonRes = Object.assign({ index: value.data }, jsonRes);
                })

                res.json({data: jsonRes});

            }
        }
    }) 

I even tried using global var , but even it's not working, how can I use index as well as value argument at the same time

What is the JSON structure that you want ?

if you want a json like :

{
  0: "my first value",
  1: "second"
}

You just miss [] around index, here you put 'index' as a key not the value of index. So you override the index key in each iteration.

Here is the code that use the value of index as a key in a json.

jsonRes = Object.assign({[index]: value.data}, jsonRes)

See here for a working example with more examples : https://repl.it/@Benoit_Vasseur/nodejs-playground

Object.assign mutates the left-most parameter. it does not produce a new object. Since you are passing a literal object every time the jsonRes is going to be the last result.

Put jsonRes in the left instead - Object.assign(jsonRes, {index: value.data})

You might want to use a simple reduce instead of forEach and Object.assign :

} else {
  var jsonRes = result.reduce((r, v, i) => {r[i] = v.data; return r}, {});
  res.json({data: jsonRes});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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