'Adding items to an object through the .push() method
I'm doing a loop through few input elements of 'checkbox' type. After that, I'm adding values and checked attributes to an array. This is my code:
var stuff = {};
$('form input[type=checkbox]').each(function() {
stuff[$(this).attr('value')] = $(this).attr('checked');
});
This works fine, but I'm just wondering if I can do the exact same thing with .push() method in Jquery?
I've tried something like this but it doesn't work:
stuff.push( {$(this).attr('value'):$(this).attr('checked')} );
Edit:
I was trying to use .push() method on Object, but .push() is actually just a method of Array Object.
Solution 1:[1]
so it's easy)))
Watch this...
var stuff = {};
$('input[type=checkbox]').each(function(i, e) {
stuff[i] = e.checked;
});
And you will have:
Object {0: true, 1: false, 2: false, 3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff['row'+i] = e.checked;
});
You will have:
Object {row0: true, row1: false, row2: false, row3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff[e.className+i] = e.checked;
});
You will have:
Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
Solution 2:[2]
stuff is an object and push is a method of an array. So you cannot use stuff.push(..).
Lets say you define stuff as an array stuff = []; then you can call push method on it.
This works because the object[key/value] is well formed.
stuff.push( {'name':$(this).attr('checked')} );
Whereas this will not work because the object is not well formed.
stuff.push( {$(this).attr('value'):$(this).attr('checked')} );
This works because we are treating stuff as an associative array and added values to it
stuff[$(this).attr('value')] = $(this).attr('checked');
Solution 3:[3]
This is really easy: Example
//my object
var sendData = {field1:value1, field2:value2};
//add element
sendData['field3'] = value3;
Solution 4:[4]
Another way of doing it would be:
stuff = Object.assign(stuff, {$(this).attr('value'):$(this).attr('checked')});
Read more here: Object.assign()
Solution 5:[5]
Today you can use destructuring to make these things for you!
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Destructuring works both for arrays and objects too. You can just put:
let stuff = {
text: "value"
}
// create some other value
const anotherVariable = 10
stuff = {
...stuff,
anotherVariable
}
console.log(stuff)
And the output will be: {text: "value", anotherVariable: 10}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Иван Олейник |
| Solution 2 | AnNaMaLaI |
| Solution 3 | C47 |
| Solution 4 | Kenny Horna |
| Solution 5 | Narciso Ferreira |
