0

I am not able to get a key and value pairs using the each function of jquery. How to get the key and values object using jQuery each function..?

my try:

var result = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';

$.each($.parseJSON(result), function(n, v) {
    console.log({n: v});
});

result i am getting as:

Object {n: "John"} 
Object {n: "Doe"} 
Object {n: "[email protected]"} 
Object {n: "123 dead drive"} 

but i am looking for :

    Object {FirstName: "John"} 
    Object {LastName: "Doe"} 
    Object {Email: "[email protected]"} 
    Object {Phone: "123 dead drive"} 

what is the correct approach to get this done..?

Thanks in advance.

5 Answers 5

2

You need

$.each($.parseJSON(result), function(n, v) {
    var obj = {};
    obj[n] = v;
    console.log(obj);
});
Sign up to request clarification or add additional context in comments.

Comments

1
$.each($.parseJSON(result), function(n, v) {
    console.log('{'+n +': '+ v +'}');    
});

Comments

0
$.each($.parseJSON(result), function(n, v) {
    console.log(n +":"+ v );
});

{} treated as object.You log variable as object.

Comments

0

Here you go:

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';

var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
    alert(k + ': ' + v);
});

Live Demo

Comments

-1

will give the desired output

var arr = [];

$.each($.parseJSON(result), function(n, v) {
        arr[n] = v;    
    });

console.log(arr);

3 Comments

This will not work, because basic array cannot be associative. You need arr = {}; here.
It is giving the desired output
There is no need for <code> tags, simply indent with 4 spaces.

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.