[英]To loop within array of arrays
In my below code Im am not able to fetch data within array 在我下面的代码中,我无法获取数组内的数据
var str = "Service1|USER_ID, Service1|PASSWORD"
var str_array = str.split(',');
console.log(str_array)
for(var i = 0; i < str_array.length; i++)
{
str_array[i] = str_array[i].split('|');
}
console.log(str_array)
This is the response from above code 这是上面代码的响应
/* [ [ 'Service1', 'USER_ID' ],
[ 'Service1', 'PASSWORD' ] ]*/
I want response to be in two different array like below 我希望响应位于以下两个不同的数组中
var array1 = ['Service1']
var array2 = ['USER_ID','PASSWORD']
Any help on this will be really helpful 任何帮助都会非常有帮助
Since you're on Node, you can do this: 由于您位于Node上,因此可以执行以下操作:
var str = "Service1|USER_ID, Service1|PASSWORD";
var result = str.split(',').reduce(function(collected,splitByComma){
var splitData = splitByComma.split('|');
var key = splitData[0].replace(/\s+/gi,''); //Might want to improve this "trim"
var data = splitData[1];
if(!collected.hasOwnProperty(key)) collected[key] = [];
collected[key].push(data);
return collected;
},{});
console.log(JSON.stringify(result)); //{"Service1":["USER_ID","PASSWORD"]}
//result.Service1[0] == USER_ID
//result.Service1[1] == PASSWORD
It's not wise to place stuff in separate places. 将内容放在单独的位置是不明智的。 You could have them under an object key though.
您可以将它们放在对象键下。 If service name is variable, then you could do:
如果服务名称是可变的,则可以执行以下操作:
var serviceName = "Service1";
result[serviceName][0] == USER_ID
result[serviceName][1] == PASSWORD
We can have a simple Regex solution 我们可以有一个简单的正则表达式解决方案
var res = "Service1|USER_ID, Service1|PASSWORD".split(/[\|,]/g);
var ar1 = [], ar2 = [];
res.forEach(function(em,i){
if(i%2==0) {
if(ar1.indexOf(em.trim())<0){
ar1.push(em.trim());
}
} else {
ar2.push(em.trim());
}
});
//ar1 and ar2 will contain expected results // ar1和ar2将包含预期结果
As I have understand your question, you will want an array associated with each service key, to be able to do 据我了解您的问题,您将需要一个与每个服务密钥关联的数组,以便能够
services.service1 and get ['username', 'password' ] ? services.service1并获取['username','password']? If so, here's a solution:
如果是这样,请提供以下解决方案:
var str = "Service1|USER_ID, Service1|PASSWORD".replace(', ', ',').split(','), //[ 'Service1|USER_ID', 'Service1|PASSWORD' ]
out = {};
str.forEach(function(element){
var key, value;
element = element.split('|');
key = element[0].trim();
value = element[1].trim();
out[key] = out[key] || []; // ensures we can push the value into an array
out[key].push(value);
});
console.log(out); //{ Service1: [ 'USER_ID', 'PASSWORD' ] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.