HelpASisterOut
HelpASisterOut

Reputation: 3185

Parse array with format key-value in nodejs

I am receiving a JSON to my nodeJS app in the following format from an ajax call; where i receive an array and i send it using

$.ajax({
                    type:'POST',
                    url:'/check',
                            data:JSON.stringify(array1),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json"})  
    })

i receive it as follows :

[{ key: 'name',  value: 'lorem ipsum' }
{ key: 'language', value: 'en' }
{ key: 'color', value: 'red' } 
{ key: 'resolution', value: [ 1920, 1080 ] } ]

I want to save each of these values in variables, something like this :

app.post('/check', function(req, res) 
{   
    var obj = req.body;
    var keys = Object.keys(obj);
    for (var i = 0; i < keys.length; i++) { 
       console.log(keys[i])

       //   what i want to do:
       //   if (keys[i] == 'name') {
       //   var name = value of this key, 
       //   in this example 
       //   var name = "lorem ipsum" 
       //   var language = "en" 
       //   var color = "red" 
       //   var resolution = [ 1920, 1080 ]            
    }
    res.send("ok");
});

I am not sure how to loop through the keys of the JSON and associate the value for the key in my code

Currently console.log(keys[i]) returns an index number, which is not useful to me

Upvotes: 0

Views: 2427

Answers (6)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27222

Few observations :

  • As per the OP, var obj is an array of objects. Hence, Object.keys(obj) will result the array of the indexes of the elements of an array.
  • We can try to iterate the array using Array.map() method and then we can map the values of each object into the variable.

DEMO

var obj = [{ key: 'name',  value: 'lorem ipsum' },
{ key: 'language', value: 'en' },
{ key: 'color', value: 'red' },
{ key: 'resolution', value: [ 1920, 1080 ] }];

obj.map(item => {
  if (item.key == 'name') {
    var name = item.value;
    console.log(name); // lorem ipsum
  }
});

Upvotes: 1

Logar
Logar

Reputation: 1248

If you indeed use JSON, then a simple JSON.parse() will transform your JSON string into an Object of the shape you describe.

If you want to loop through all of your ojbect properties, there is 3 convenient methods for this :

  • Object.keys will return an array of all your object keys

  • Object.values will return an array of all your object values

  • Object.entries will return an array of arrays containing the key as the first element, and the value as second.

Example code :

const obj = { key: 'name',  value: 'lorem ipsum' };

Object.entries(obj).map(([key, value]) => {
    console.log(key);
    console.log(value);
});
// will log 'key', 'name', 'value', 'lorem ipsum'

If you have an array of objects :

const arr_of_obj = [
                       { key: 'name',  value: 'lorem ipsum' },
                       { key: 'name2',  value: 'lorem ipsum' }
                   ];

arr_of_obj.map(item => {
    Object.entries(item).map(([key, value]) => {
        console.log(key);
        console.log(value);
    })
});

Edit

If I got you right, what you really want is to create a new object with your input keys properties as keys and values properties as values :

const arr_of_obj = [
                       { key: 'firstName',  value: 'john' },
                       { key: 'lastName',  value: 'doe' }
                   ];

const newObj = arr_of_obj.reduce((memo, {key, value}) => {
    return {
        ...memo,
        [key]: value
    }
}, {});

console.log(newObj);
//will output { firstName: 'john', lastName: 'doe' }

Upvotes: 0

Adrian Baginski
Adrian Baginski

Reputation: 336

Try this code snippet using regex to parse your input:

var myString = `{ key: 'name',  value: 'lorem ipsum' }
{ key: 'language', value: 'en' }
{ key: 'color', value: 'red' } 
{ key: 'resolution', value: [ 1920, 1080 ] }`;
var myRegexp = /(?:key: ')([a-z]*)(?:')/g;
match = myRegexp.exec(myString);
while (match) {
  console.log(match[1])
  match = myRegexp.exec(myString);
}

Upvotes: 1

Thai Duong Tran
Thai Duong Tran

Reputation: 2522

The format you receive

{ key: 'name',  value: 'lorem ipsum' }
{ key: 'language', value: 'en' }
{ key: 'color', value: 'red' } 
{ key: 'resolution', value: [ 1920, 1080 ] }

is an array of key-value object. So called Object.keys on it will definitely return an array of index number.

What you want to do is simply loop through the array, check the key value of each object and action on the value accordingly, below is an example on ES6 with supported on NodeJS 6 and later version:

var obj = req.body;

obj.map(({key, value}) => { 
  if (key === 'name') {
  // Do something on value
  } 
})

Upvotes: 0

tkint
tkint

Reputation: 331

I think your JSON is malformed, and you may want it to look that way:

{
    "name": "lorem ipsum",
    "language": "en",
    "color": "red",
    "resolution": "[ 1920, 1080 ]"
}

Like that, you can access the data like that:

var obj = req.body;
var name = obj.name;
var language = obj.language;
var color = obj.color;
var resolution = obj.resolution;

Upvotes: 0

Adrian Baginski
Adrian Baginski

Reputation: 336

First off, don't name any of your variables "keys" :)

Secondly, you should really work on the backend implementation to return valid JSON code, instead of line-to-line objects.

Upvotes: 0

Related Questions