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

9
  • 4
    Either you have JSON (that is, a string in JSON format) or you have an array - which is it? Commented May 28, 2018 at 9:38
  • Please read What is the difference between JSON and Object Literal Notation? Commented May 28, 2018 at 9:40
  • what does console.log(obj) show you ? Commented May 28, 2018 at 9:40
  • 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. Commented May 28, 2018 at 9:46
  • 1
    Then you should have included the [] around the data that you say you're receiving, otherwise people will answer based on wrong data. Commented May 28, 2018 at 9:52

6 Answers 6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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
  }
});

Comments

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' }

6 Comments

Weirdly; it is logging the key as 0,1,2,3 ... and the value as { key: 'name', value: 'lorem ipsum' }...
Because you have an array of objects. I'm editing my answer atm
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 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
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
|
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.

1 Comment

I can't control the json, im receiving it from an external api
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;

2 Comments

I don't control the json; i receive it from an API
The answer of Sirko is probably the best then, you have to split your body based on line and work on each line.
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
  } 
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.