Reputation: 31
I'm trying to append the object from the array. I try to loop through the array but it only appends one element of the array to the object. fiddle: https://jsfiddle.net/maherafrasiab/9ehkfvoc/3/
Edited:
var shers = {};
// the .pbgmain will return the following array.
var all = [{sher: "some text"},{sher: "some text"},{sher: "some text"}];
//basically i want to convert the above array into object.
var data = $('.pbgmain').each(function(i) {
datas = $(this).text().trim();
all.push({sher: datas})
for(var i = 0; i < 10; i++) {
shers = all[i];
}
});
Upvotes: 1
Views: 101
Reputation: 155075
the
.pbgmain
will return the following array.var all = [{sher: "some text"},{sher: "some text"},{sher: "some text"}];
You just need this (and you don't need to use jQuery!):
const elements = document.querySelectorAll( '.pbgmain' );
const elementArray = Array.from( elements );
const elementTexts = elementArray.map( e => e.textContent.trim() );
const asArrayOfObjects = elementTexts.map( text => ( { sher: text } ) );
console.log( asArrayOfObjects );
This can be shortened to this if you want to be more succint:
const asArrayOfObjects = Array.from( document.querySelectorAll( '.pbgmain' ) ).map( e => ( { sher: e.textContent.trim() } );
console.log( asArrayOfObjects );
Upvotes: 1