在Javascript数组中连接值

时间:2022-05-26 21:15:26

Say I have:

说我有:

var Certificated = {}

Sub items are added dynamically and variate. Possible outcome:

子项是动态添加和变量的。可能的结果:

var Certificated = {
    Elementary: ["foo","bar", "ball"]
    MiddleSchool: ["bar", "crampapydime"]
};

I want to do the following:

我想做以下事情:

Certificated.Elementary = Certificated.Elementary.join("");

Except I need it to do that on all of the objects inside.

除了我需要它在内部的所有对象上执行此操作。

Keep in mind I can't know for sure the titles of nor how many objects will be inside Certificated.

请记住,我无法确定Certificated内部的标题和对象数量。

My question is how can I use .join("") on all elements inside Certificated, without calling each one specifically?

我的问题是如何在Certificated中的所有元素上使用.join(“”),而不是专门调用每个元素?

EDIT: I am aware .join() is for arrays and the objects inside Certificated are going to be arrays. Therefore the join method.

编辑:我知道.join()用于数组,Certificated中的对象将是数组。因此连接方法。

1 个解决方案

#1


2  

Does this work?

这有用吗?

for (var key in Certificated) {
    if (Certificated.hasOwnProperty(key)) {
        Certificated[key] = Certificated[key].join("");
    }
}

It loops through all properties of Certificated, and makes a quick safe check for the key being a real property, then uses bracket notation - [""] - to do your join.

它循环遍历Certificated的所有属性,并快速安全地检查密钥是否为真实属性,然后使用括号表示法 - [“”] - 进行连接。

Quick question - are you sure you want to use join? I know you just provided an example, but you can't call join on a string...it's for arrays. Just wanted to make sure you knew.

快速提问 - 您确定要使用加入吗?我知道你刚刚提供了一个例子,但你不能在字符串上调用join ...它是用于数组的。只是想确保你知道。

Here's a jsFiddle of my code working with arrays being used for the properties:

这是我的代码的jsFiddle,使用用于属性的数组:

http://jsfiddle.net/v48dL/

Notice in the browser console, the properties' values are strings because the join combined them with "".

请注意,在浏览器控制台中,属性的值是字符串,因为连接将它们与“”组合在一起。

#1


2  

Does this work?

这有用吗?

for (var key in Certificated) {
    if (Certificated.hasOwnProperty(key)) {
        Certificated[key] = Certificated[key].join("");
    }
}

It loops through all properties of Certificated, and makes a quick safe check for the key being a real property, then uses bracket notation - [""] - to do your join.

它循环遍历Certificated的所有属性,并快速安全地检查密钥是否为真实属性,然后使用括号表示法 - [“”] - 进行连接。

Quick question - are you sure you want to use join? I know you just provided an example, but you can't call join on a string...it's for arrays. Just wanted to make sure you knew.

快速提问 - 您确定要使用加入吗?我知道你刚刚提供了一个例子,但你不能在字符串上调用join ...它是用于数组的。只是想确保你知道。

Here's a jsFiddle of my code working with arrays being used for the properties:

这是我的代码的jsFiddle,使用用于属性的数组:

http://jsfiddle.net/v48dL/

Notice in the browser console, the properties' values are strings because the join combined them with "".

请注意,在浏览器控制台中,属性的值是字符串,因为连接将它们与“”组合在一起。