1

I'm trying to iterate over all inputs in the page and build a JSON to send via post request to backend:

function getBody() {
         var blocks = $('.list-group-item').map(function(idx, elem) {

            var inputs = $(elem).find('.block-input').map(function (idi, input) {
               //Probably this part needs to change
               return {
                  [$(input).attr('name')]: $(input).val()
               };
            }).get();


            return {
               id: $(elem).data('id'),
               name: $(elem).data('name'),
               inputs,
            };
         }).get();

         var products_json = JSON.stringify(blocks,null,'\t');
         console.log(products_json)
};

It works, and this is my result:

[
    {
        "id": 13,
        "name": "About us",
        "inputs": [
            {
                "title": "How we started"
            },
            {
                "paragraph": "We started 5 years ago in a ..."
            }
        ]
    }
]

I want to get back a single object for all inputs and not an object per input, how do I return a key-value pair to object with map()? I want the result to look like this:

[
    {
        "id": 13,
        "name": "About us",
        "inputs": {
            "title": "How we started"
            "paragraph": "We started 5 years ago in a ..."
        }
    }
]
BenNov
  • 1,086
  • 2
  • 10
  • 18
  • Does this answer your question? [How can I add a key/value pair to a JavaScript object?](https://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object) – Ryan Wilson Mar 30 '20 at 15:30

3 Answers3

1

Don't use map to create the inputs object. Use a loop that adds a key/value element to an object.

function getBody() {
  var blocks = $('.list-group-item').map(function(idx, elem) {
    var inputs = {};
    $(elem).find('.block-input').each(function(idi, input) {
      inputs[$(input).attr('name')] = $(input).val();
    });

    return {
      id: $(elem).data('id'),
      name: $(elem).data('name'),
      inputs,
    };
  }).get();

  var products_json = JSON.stringify(blocks, null, '\t');
  console.log(products_json)
};
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You can fix this by updating the return statement inside getBody() like:

return {
   id: $(elem).data('id'),
   name: $(elem).data('name'),
   inputs: Object.assign({}, ...inputs),
};
palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

You can convert inputs array to object using Array.reduce().

const inputsObject = inputs.reduce((accumulator, currentValue) => {
const [firstKey] = Object.keys(currentValue);
    accumulator[firstKey] = currentValue[firstKey];
    return accumulator;
}, {})

Then return it,

return {
           id: $(elem).data('id'),
           name: $(elem).data('name'),
           inputs: inputsObject,
        };