0

How do I convert some elements of my form to a JSON?

I want the JSON data not based on "name": "value", but "value1": "value2".

Where "value1" is the input element 1 and "value2" is the input element 2.

And what if I want to add an object to the previous JSON data? For example,

dataBefore = {"key": "1"}; 

dataAfter = {"key": "1", "data": "2"};

The code have i tried,

var person = {};
var key = $('#com-key2').val();
person[key] = $('#com-value2').val();

And the UI like this, form example

Note: ID of all input element is same

How to do that? Sorry if the language is hard to understand

  • please share some code you have tried already.. or some more context – Ajanth Jun 12 '18 at 00:51
  • Possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – Vikasdeep Singh Jun 12 '18 at 00:54

3 Answers3

0

I'm not exactly sure what you mean for the first part, but to add an object:

dataBefore = {"key": "1"};

dataBefore["data"] = "2"

dataBefore = {"key": "1", "data": "2"};

Edit: This might be what you're looking for

var obj = {};
var key = document.getElementById('myInput').value;
var text = document.getElementById('myOtherInput').value;
obj[key] = text;
Andrew
  • 531
  • 1
  • 6
  • 20
0

I'm not sure if this is an answer to your question.

If there's wrong, please tell me.

var obj = {"key1":"value1","key2":"value2","key3":"value4"};
var index = 0;
for(var key in obj){
    $('.key').eq(index).val("new_"+key);
    $('.value').eq(index).val("new_"+obj[key]);
    index++;
}

$('.container').each(function(){
  var key = $(this).find('.key').first().val();
  var value = $(this).find('.value').first().val();
  obj[key] = value;
})

console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input class="key" name="key1"/>
<input class="value" name="value1"/>
</div>
<div class="container">
<input class="key" name="key2"/>
<input class="value" name="value2"/>
</div>
<div class="container">
<input class="key" name="key3"/>
<input class="value" name="value3"/>
</div>
Terry Wei
  • 1,521
  • 8
  • 16
0

First, you do NOT need jQuery for combining two objects into one.

Second, re-reading your question: having duplicate element id attributes is NOT VALID HTML. If you want to get everything in one go with a specificity one selector, then do <input ... class="form__input" /> and use this as your jQuery selector var $inputs = $(".form__input");

Object.assign will merge two objects and will work in most browsers (MSIE needs a shim)

var a = { a: 1 }, b = { b: 2 }, c;

c = Object.assign( {}, a, b );

console.log( JSON.stringify( c ) );

// { "a": 1, "b": 2 }
Stand__Sure
  • 253
  • 1
  • 13