0

I'm working on a payment form and want to create an array of JS objects from the below HTML. The objects would have the following structure:

var myObject = {
    merchantGuid: 'string value',
    accessToken: 'string value',
    active: boolean,
    url: 'string value'
};

The DOM would look like this:

<input type="hidden" data-active="false" name="tokenDatas[0].merchantGuid" value="abc1234" />
<input type="hidden" data-active="false" name="tokenDatas[0].accessToken" value="586b30a1" />
<input type="hidden" data-active="false" name="tokenDatas[0].active" value="false" />
<input type="hidden" data-active="false" name="tokenDatas[0].url" value="https://test.example.com/api" />

<input type="hidden" data-active="true" name="tokenDatas[1].merchantGuid" value="def6789" />
<input type="hidden" data-active="true" name="tokenDatas[1].accessToken" value="ca1v2d17" />
<input type="hidden" data-active="true" name="tokenDatas[1].active" value="true" />
<input type="hidden" data-active="true" name="tokenDatas[1].url" value="https://test.example.com/api" />
1

1 Answer 1

3

You can use this JS code.

let fields = {};
    let inputs = document.querySelectorAll('input');
    for(let i = 0; i < inputs.length; i++){
      let data = inputs[i].getAttribute("name");
      fields[data] = data;
}
<input type="hidden" data-active="false" name="tokenDatas[0].merchantGuid" value="abc1234" />
<input type="hidden" data-active="false" name="tokenDatas[0].accessToken" value="586b30a1" />
<input type="hidden" data-active="false" name="tokenDatas[0].active" value="false" />
<input type="hidden" data-active="false" name="tokenDatas[0].url" value="https://test.example.com/api" />

<input type="hidden" data-active="true" name="tokenDatas[1].merchantGuid" value="def6789" />
<input type="hidden" data-active="true" name="tokenDatas[1].accessToken" value="ca1v2d17" />
<input type="hidden" data-active="true" name="tokenDatas[1].active" value="true" />
<input type="hidden" data-active="true" name="tokenDatas[1].url" value="https://test.example.com/api" />

Sign up to request clarification or add additional context in comments.

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.