0

I have a matrix with "seccion" keys and I want to join it by "seccion". Help me here I leave an example. I am already grateful for your support. Sorry for my English

At the beginning I have this then try to join them:

{0: {seccion: "0", stitulo: "titulo_test1"}, 
 1: {seccion: "0", ssub: "sub_test1"},
 2: {seccion: "1", stitulo: "titulo_test2"},
 3: {seccion: "1", ssub: "sub_test2"}
}

What I do is go through all the objects with an assigned class, but the "i" counter overwrites them:

var secciones={};
$('#formSecciones').find('.secc').each(function(i,s) {
    secciones[`$(s).closest('.dd-item').attr('data-id')] = {};
    secciones[`$(s).closest('.dd-item').attr('data-id')][i] = {};
    secciones[`$(s).closest('.dd-item').attr('data-id')][i][s.name] = s.value;
});

Result:

{0:{1:{ssub: "sub_test1"}},
 1:{3:{ssub: "sub_test2"}}
}

This is what I want to get:

{0: {ssub: "sub_test1", stitulo: "titulo_test1"},
 1: {stitulo: "titulo_test2", ssub: "sub_test2"}
}
3
  • Your code isn't operating on the object, it's operating on DOM elements. Commented Jun 18, 2019 at 17:22
  • You have a bunch of unmatched backticks. Commented Jun 18, 2019 at 17:23
  • Treating an object like an array? Commented Jun 18, 2019 at 17:32

1 Answer 1

1

You should only create a new object if the object doesn't already exist at that key.

Also, you don't want nested arrays, so you don't need [i] in the target of the assignment.

var secciones={};
$('#formSecciones').find('.secc').each(function(i,s) {
    var id = $(s).closest('.dd-item').attr('data-id');
    if (!secciones[id]) {
        secciones[id] = {};
    }
    secciones[id][s.name] = s.value;
});
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much I am very grateful, I had already tried something similar but I do not remember what was wrong.

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.