简体   繁体   中英

How to most efficiently generate string from array of objects in javascript?

I have the following:

var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}]

I want to generate a string like this: "Jordan,6|Jake,7|Mark,10"

What is the most efficient way to do this?

I am currently using:

var studentstr = "";
for(var i = 0; i < students.length; i++) {
  studentstr = students['name'] + "," + students['age'] + "|"
}
studentstr = studentstr.substring(0, studentstr.length - 1);

Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation? The resulting string contains both keys in the object and not a single join on one object in the property.

You can map each student object to a string and then join them all with | :

var studentstr = students.map(function (student) {
    return student.name + ',' + student.age;
}).join('|');

Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation?

No.

Yes, using string concatenation in a loop is costly. The string grows for each iteration, and each time you have to copy the entire previous string to create the new version. The execution time of the loop grows exponentially to the number of items.

You can put the string for each object in an array, then join them together:

 var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}]; var items = []; for (var i = 0; i < students.length; i++) { items.push(students[i].name + ',' +students[i].age); } var str = items.join('|'); // display result in snippet document.write(str); 

map works well for this:

var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];
var result = students.map(function(student) {
    return student.name + ',' + student.age;
});
alert(result.join('|'));

Try this and see your console:

var string = '';
for (var s in students) {
    string += students[s].name + ', ' + students[s].age + ' | ';
}

console.log(string);

Fiddle: http://jsfiddle.net/80ss0u14/

I do not think it is costly to go on with such approach. It may be the most efficient way to iterate through the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM