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 ..."
        }
    }
]
1

3 Answers 3

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

Comments

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

Comments

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

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.