Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

arrays - for loop not working when appending object in javascript

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];
        }
    });
question from:https://stackoverflow.com/questions/65841513/for-loop-not-working-when-appending-object-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...