Three JavaScript Techniques to Join a JSON Array Field into a CSV String
Learn three JavaScript approaches—using map with join, map with manual concatenation, and reduce—to extract a specified property from each object in a JSON array and combine the values into a comma-separated string, with full code examples.
When a backend returns a JSON array, developers often need to concatenate a particular property of each object into a single comma‑separated string.
Method 1: map + join
const jsonArr = [
{'id': '1', 'name': 'a1'},
{'id': '2', 'name': 'a2'},
{'id': '3', 'name': 'a3'},
{'id': '4', 'name': 'a4'},
{'id': '5', 'name': 'a5'}
];
const joinJsonField = (jsonArr, fieldName) => {
let a = [];
jsonArr.map(item => {
a.push(item[fieldName]);
});
let b = a.join(',');
return b;
};
joinJsonField(jsonArr, 'name'); // 'a1,a2,a3,a4,a5'Method 2: map + manual concatenation + substring
const joinJsonField = (jsonArr, fieldName) => {
let a = '';
jsonArr.map(item => {
a += item[fieldName] + ',';
});
return a.substring(0, a.length - 1);
};
joinJsonField(jsonArr, 'name'); // 'a1,a2,a3,a4,a5'Method 3: reduce + concatenation
const joinJsonField3 = (jsonArr, fieldName) => {
const result = jsonArr.reduce((pre, cur, index) => {
if (index === 0) return pre.concat(cur[fieldName]);
else return pre.concat(',' + cur[fieldName]);
}, '');
return result;
};
joinJsonField3(jsonArr, 'name'); // 'a1,a2,a3,a4,a5'An animated GIF illustrates the transformation process.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Trendsetter
Latest articles, video tutorials, and open-source projects on React, Vue, Angular, Ionic, React Native, Node.js, Mini Programs, and other cutting-edge technologies. A community for sharing and discussing full-stack development trends.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
