根据不同的参数javascript创建一个字符串

时间:2016-11-03 13:33:34

标签: javascript arrays string

我想根据用户输入生成一个字符串,它应该如下所示: 1234-2016-abc12-3232 ,我有7个选项,如 roll_number user_id user_name 年度部门 subject_code 。此选项的顺序是用户定义。例如:用户可以说首先需要 user_name 然后 subject_code 然后 roll_number 等等,用户也可以选择他想要的角色数量特殊选项意味着他可以说 roll_number 中的最后2个字符, user_name 中的前3个字符,依此类推。

===我尝试了什么===

首先我捕获了4个阵列中的所有信息:

第一个数组是:

var selectedOptions = ['user_name', 'roll_number', 'subject_code', 'class'];

所以我得到了我必须选择的选项列表    字符串创建。

第二个数组是:

var sequence = [
                    { key:'user_name', value:2 },
                    { key:'subject_code', value:3 },
                    { key:'class', value:1 },
                    { key:'roll_number', value:4 },
                ];

这个数组给出了选项序列。

第三个​​数组是:

var alignment = [
            { key:'user_name', value:'left' },
            { key:'subject_code', value:'left' },
            { key:'class', value:'right' },
            { key:'roll_number', value:'left' },
        ];

它提供了对齐的知识,例如,如果 roll_number 是123456,并且用户从右边选择长度为3,那么应该采用456,所以这是左右信息。

第四个数组是:

var lengthOfOptions = [
            { key:'user_name', value:3 },
            { key:'subject_code', value:4 },
            { key:'class', value:2 },
            { key:'roll_number', value:5 },
        ];

===接着===

此选项的值:

        var user_name = "1234abcd";
        var subject_code = "567890";
        var class = "2016";
        var roll_number = "123";

现在使用for loop我得到了选项的名称,然后我试图得到序列,但我无法获得特定选项的序列,因为我在for loop里面而我不是如果你有任何简单的方法或指南,请确保我首先得到顺序或选项名称请帮助,我的观点是我需要循环内循环但我不知道如何?感谢。

== EDIT ==

我的循环代码是

            sequence.sort(function(a, b) {
                return parseFloat(a.value) - parseFloat(b.value);
            });
            for (var i = 0; i <= sequence.length - 1; i++){
                console.log("The key is :", sequence[i]['key']);
                console.log("The value is :", sequence[i]['value']);
            }

在此之后该怎么做我无法理解。

2 个答案:

答案 0 :(得分:1)

在您的情况下,roll_number将为空,因此您将在最终字符串的末尾看到连字符

&#13;
&#13;
var selectedOptions = ['user_name', 'roll_number', 'subject_code', 'class'];
var sequence = [{
  key: 'user_name',
  value: 2
}, {
  key: 'subject_code',
  value: 3
}, {
  key: 'class',
  value: 1
}, {
  key: 'roll_number',
  value: 4
}, ];

var alignment = [{
  key: 'user_name',
  value: 'left'
}, {
  key: 'subject_code',
  value: 'left'
}, {
  key: 'class',
  value: 'right'
}, {
  key: 'roll_number',
  value: 'left'
}, ];

var lengthOfOptions = [{
  key: 'user_name',
  value: 3
}, {
  key: 'subject_code',
  value: 4
}, {
  key: 'class',
  value: 2
}, {
  key: 'roll_number',
  value: 5
}, ];

var object = {
  "user_name": "1234abcd",
  "subject_code": "567890",
  "class": "2016",
  "roll_number": "123"
}

var result = [];

//Iterate each option
for (var i = 0; i < selectedOptions.length; i++) {
  var key = selectedOptions[i];
  var seq = sequence.filter(function(v, i) {
    return v.key === key;
  })[0].value; //Get the sequence number
  var align = alignment.filter(function(v, i) {
    return v.key === key;
  })[0].value; //Get the alignement value
  var length = lengthOfOptions.filter(function(v, i) {
    return v.key === key;
  })[0].value; //Get the length value

  var string = object[key]; //Get the string to modify
  if (align === "left") {
    string = string.slice(length);
  } else {
    string = string.slice(0, string.length - length);
  }

  result[seq - 1] = string; //Add the string in an array at the correct sequence index.
}

var finalString = result.join("-"); //Concat all the strings with '-'

console.log(finalString);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

首先,您可以对sequence进行排序,然后使用Array.prototype.reduce来计算每个length的{​​{1}}和alignment,并将其连接到所需的selectedOptions字符串:

演示如下:

var selectedOptions = ['user_name', 'roll_number', 'subject_code', 'class'];
var sequence = [{ key:'user_name', value:2 },{ key:'subject_code', value:3 },{ key:'class', value:1 },{ key:'roll_number', value:4 },];
var alignment = [{ key:'user_name', value:'left' },{ key:'subject_code', value:'left' },{ key:'class', value:'right' },{ key:'roll_number', value:'left' },];
var lengthOfOptions = [{ key:'user_name', value:3 },{ key:'subject_code', value:4 },{ key:'class', value:2 },{ key:'roll_number', value:5 },];

// input values
var options={user_name:"1234abcd",subject_code:"567890", class:"2016",roll_number:"123"};

var result = sequence.sort(function(a, b) {
  return a.value - b.value;
}).reduce(function(prev, curr) {
  // if sequence elements are selected options
  if (selectedOptions.indexOf(curr.key) !== -1) {
    // find length and alignment
    var length = Math.min(lengthOfOptions.filter(e => e.key == curr.key)[0].value, options[curr.key].length);
    var align = alignment.filter(e => e.key == curr.key)[0].value;

    // extract the substring from input
    if (align == "left") {
      prev.push(options[curr.key].slice(0, length));
    } else {
      prev.push(options[curr.key].slice(-length));
    }
    return prev;
  }
}, []).join('-');

console.log(result);

注意计算长度时使用的Math.min - 检查lengthOption是否超出输入值大小。

修改

因此,如果您想padding 0 lengthOption以防var selectedOptions = ['user_name', 'roll_number', 'subject_code', 'class']; var sequence = [{ key:'user_name', value:2 },{ key:'subject_code', value:3 },{ key:'class', value:1 },{ key:'roll_number', value:4 },]; var alignment = [{ key:'user_name', value:'left' },{ key:'subject_code', value:'left' },{ key:'class', value:'right' },{ key:'roll_number', value:'left' },]; var lengthOfOptions = [{ key:'user_name', value:3 },{ key:'subject_code', value:4 },{ key:'class', value:2 },{ key:'roll_number', value:5 },]; var options={user_name:"1234abcd",subject_code:"567890", class:"2016",roll_number:"123"}; var result = sequence.sort(function(a, b) { return a.value - b.value; }).reduce(function(prev, curr) { if (selectedOptions.indexOf(curr.key) !== -1) { var lengthOption = lengthOfOptions.find(e => e.key == curr.key).value; var align = alignment.find(e => e.key == curr.key).value; var padding = Math.max(lengthOption - options[curr.key].length, 0); if (align == "left") { prev.push(Array(padding + 1).join(0) + options[curr.key].slice(0, Math.min(lengthOption, options[curr.key].length))); } else { prev.push(Array(padding + 1).join(0) + options[curr.key].slice(-Math.min(lengthOption, options[curr.key].length))); } return prev; } }, []).join('-'); console.log(result);超过输入值,您可以使用此值。干杯!

-root
    - example
        -package.json
    -lib
      -lib.js
    -src
      -test.js
    package.json