1

I have a jQuery function which returns me the following string

[{"email":"[email protected]"},{"password":"test"}]

and I want to convert it to this

{"email":"[email protected]","password":"test*"}

This is the code I'm currently using.

var obj = $.map(inputs, function (x, y) {
    var ret = {};
    ret[x.name] = $(x).val();
    return ret;
});

var jsonData = JSON.stringify(obj);
3
  • Can you please add the code which returns that output? Commented Feb 3, 2016 at 11:14
  • var obj = $.extend({},json1,json2); console.log(obj); try from api.jquery.com/jquery.extend Commented Feb 3, 2016 at 11:14
  • added the code snippet i am using Commented Feb 3, 2016 at 11:16

4 Answers 4

4
   var inputs = [{"email":"[email protected]"},{"password":"test"}];

   var obj = {};

   $.each(inputs, function(index, item) {
     $.extend(obj, item);
   });
Sign up to request clarification or add additional context in comments.

Comments

0

You can use this:

var obj = {};

$('input').each(function(){
   obj[this.type] = this.value
});

$('pre').html(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='email' value='[email protected]'><br>
<input type='password' value='123456'><br>


<pre></pre>

Comments

0

If you receives a string, just do it:

var myNewJson =  JSON.parse(your_string);

But, I saw you are converting an array of object in a unique object. Is it you want? You can use .reduce(). More info here Array.prototype.reduce()

Comments

0

change it to

var obj = {}

$.map(inputs, function (x, y) {
   obj [x.name] = $(x).val();
});
var jsonData = JSON.stringify(obj);

Why your code isn't working the way you want to?

var obj = $.map(inputs, function (x, y) {
    var ret = {};
    ret[x.name] = $(x).val();
    return ret;
});

Simply because you are creating a new object var ret = {}; every time and setting only one value to it and then push it into an array ret[x.name] = $(x).val();. This array then you are returning return ret; which becomes part of your obj.

So, your object obj is basically an array of objects ret which has only one key x.name and value $(x).val().

By changing your code to the one I have given you will be able to get an object (which you intend to achieve) instead on an array (which you want to transform into an object).

3 Comments

This would be a better answer if you explained why this and not what the Asker tried...
@JohnHascall made the changes to explain why OP's code doesn't work.
@ssk I have explained why your code isn't working the way you want to. Have a look, hope you find it useful.

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.