0

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

HelpASisterOut
  • 3,085
  • 16
  • 45
  • 89
  • 4
    Either you have JSON (that is, a string in JSON format) or you have an array - which is it? – CertainPerformance May 28 '18 at 09:38
  • Please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str May 28 '18 at 09:40
  • what does console.log(obj) show you ? – Storm May 28 '18 at 09:40
  • Then use JSON.parse – CertainPerformance May 28 '18 at 09:42
  • @Storm it returns the full json – HelpASisterOut May 28 '18 at 09:43
  • 1
    @HelpASisterOut The data structure you posted is *not* JSON. JSON enforces double quotes on properties and values, and the whole structure is not an array or an object. It is just a collection of JSON-like objects separated by newlines. – str May 28 '18 at 09:46
  • If the result of `console.log(keys[i])` is a number then the data that loop is iterating over isn't like what you are showing in your question. It's probably an array. – devius May 28 '18 at 09:47
  • @devius it's an array returned in AJAX, but i'm returning it to the server : `data:JSON.stringify(array1)` – HelpASisterOut May 28 '18 at 09:50
  • 1
    Then you should have included the `[]` around the data that you say you're receiving, otherwise people will answer based on wrong data. – devius May 28 '18 at 09:52

6 Answers6

1

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);
}
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Adrian Baginski
  • 336
  • 1
  • 8
1

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
  }
});
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

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;
tkint
  • 321
  • 2
  • 5
0

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.

Adrian Baginski
  • 336
  • 1
  • 8
0

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
  } 
})
Thai Duong Tran
  • 2,453
  • 12
  • 15
0

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' }
Logar
  • 1,248
  • 9
  • 17
  • Weirdly; it is logging the `key` as `0,1,2,3` ... and the value as `{ key: 'name', value: 'lorem ipsum' }`... – HelpASisterOut May 28 '18 at 09:48
  • Because you have an array of objects. I'm editing my answer atm – Logar May 28 '18 at 09:50
  • It's a step closer, except that now i get the following : ` key \n name \n value \n lorem ipsum` and i still don't get how can i link each value to its key – HelpASisterOut May 28 '18 at 09:54
  • 1
    @HelpASisterOut I think your question is a bit unclear then, you should mention that you want to create a new object with keys and values attached. See my last edit – Logar May 28 '18 at 09:59
  • No not necessarily a new object, all ic are about is saving the values in variables to use later. but if creating a new json object out of the one i have is the simplest way then i guess id have to – HelpASisterOut May 28 '18 at 10:47
  • Transforming it into a json object helped. Thank you – HelpASisterOut May 28 '18 at 10:57