Reputation: 57
I have a function that looks something like this:
let result = [];
$(this).find('.js-readable').each(function(){
if (this._value().length > 0){
result.push({
[this.mainId] : this._value()
});
};
});
return result
As result I get an array that looks like this:
[{
"dpr_name3": "3"
}, {
"dpr_name1": "1"
}, {
"dpr_name4": "5"
}, {
"dpr_name2": "2"
}, {
"dfnc_cur": "181"
}, {
"doc_dt": "14.11.2017"
}]
How can I change my function to get it like this:
[{
"dpr_name3": "3",
"dpr_name1": "1",
"dpr_name4": "5",
"dpr_name2": "2",
"dfnc_cur": "181",
"doc_dt": "14.11.2017"
}]
Upvotes: 3
Views: 73
Reputation: 13346
You don't have to push into array. All you have to do is to initialize your array with an empty object as a first element then add key-value into it while looping:
let result = [{}];
$(this).find('.js-readable').each(function(){
if (this._value().length > 0){
result[0][this.mainId] = this._value;
};
});
return result
Upvotes: 1
Reputation: 386530
You could change result
to an object and assign the values to the given keys.
let result = {};
$(this).find('.js-readable').each(function(){
if (this._value().length > 0){
result[this.mainId] = this._value()
};
});
For later use, you could wrap the result in an array.
Upvotes: 0