简体   繁体   English

使用JavaScript合并数组中的对象

[英]Merge objects in array using Javascript

first post, new to programming, excited to learn! 第一篇帖子,编程新手,学习愉快!

The Problem: How do I merge all the objects (strings) into a single array? 问题:如何将所有对象(字符串)合并到单个数组中?

EX: 例如:

var myStrings = ["How", "", "do", "", "I", "", "merge", "", "these?"]

Desired result = ["How do I merge these?"]

My research: I've tried .join('') but that gives: 我的研究:我尝试过.join('')但这给出了:

Not desired result = How,,do,,I,,merge,,these?

Thank you for helping a newbie! 感谢您对新手的帮助!

You could filter with Array#filter for truthy values (like not empty strings) 您可以使用Array#filter真实值(例如非空字符串)

 value Boolean 'abc' -> true '' -> false 

and the join with ' ' . ' ' Then take it as an element of a new array. 然后将其作为新数组的元素。

 var myStrings = ["How", "", "do", "", "I", "", "merge", "", "these?"], result = [myStrings.filter(function (a) { return a; }).join(' ')]; console.log(result); 

You can do it by, 你可以做到的

var myStrings = ["How", "", "do", "", "I", "", "merge", "", "these?"];
var result = [myStrings.join(" ").replace(/\s\s/g, " ")];
console.log(result); // ["How do I merge these?"]

Try to join the array by a single space as I given above. 尝试按上面给出的单个空格join数组。 And replaces the double spaces with a single one. 并用单个空格代替双空格。 This has to be done since you are having empty strings in your array. 由于数组中有空字符串,因此必须执行此操作。

var myStrings = ["How", "", "do", "", "I", "", "merge", "", "these?"]

myStrings.join('').split(',,').join(' ');

You can use .forEach() to iterate array, if item is not empty string concatenate item to new string, else concatenate space character " " to new string. 您可以使用.forEach()来迭代数组,如果item不是空字符串,则将item连接到新字符串,否则,将空格字符" "连接到新字符串。

var res = [""];
myStrings.forEach(function(str) {res[0] += str !== "" ? str : " ";});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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