【问题标题】:Jquery array fusionjQuery 数组融合
【发布时间】:2016-08-05 07:31:01
【问题描述】:

我想将一个对象中多个数组的值合并到一个数组中,如下所示:

[1,2,3]
[4,5,6]

收件人:

[
    {name: 1, value: 4}, 
    {name: 2, value: 5}, 
    {name: 3, value: 6}
]

【问题讨论】:

  • 到目前为止您尝试过什么? StackOverflow 不是“为我编写代码”的网站。

标签: jquery arrays json


【解决方案1】:

使用Array#map方法在现有的基础上创建一个新数组。

var a = [1, 2, 3],
  b = [4, 5, 6];

// iterate over array `a` to genearate object array
var res = a.map(function(v, i) {
  // generate object ( result array element )
  return {
    name: v, // name from array `a`
    value: b[i] // value from array `b` get using index
  };
})

console.log(res);

【讨论】:

    【解决方案2】:

    您可以在一个数组上使用简单的for 循环,然后根据自己的喜好创建结果。

    var names  = [1, 2, 3],
        values = [4, 5, 6],
        result = [];
    
    for( var i = 0; i < names.length; i++ ) {
        result.push({
            name: names[i],
            value: values[i]
        });
    }
    
    console.log(result);

    【讨论】:

      【解决方案3】:
          var names = [1,2,3];
          var values =  [4,5,6];
          var result =[];
      
          for(var i=0;i<names.length;i++){
           var obj= {
             "name":names[i],
             "value": values[i]
           }
           result.push(obj);
          }
          console.log(result);
      

      【讨论】:

      • 我认为这样循环数组不是一个好主意!无论何时使用for ... in,你都应该牢记这一点:stackoverflow.com/questions/500504/…
      • 当你现在想到它时,你应该可以删除这个答案,因为它通常是不好的做法,应该在任何地方避免。 ;)
      【解决方案4】:

      arr1 = [1,2,3];
      arr2 = [4,5,6];
      
      //prepare array to fill
      obj = [];
      
      // for every item we merge them into an object and pass them into the newObj
      function merge(item, index, arr2, newObj){
        temp = {};
        temp[item] = arr2[index];
        newObj.push(temp);
      }
      
      //give the item as key, the index for the second array, and the object we want to fill
      arr1.forEach((item, index) => merge(item, index, arr2, obj));
      
      console.log(obj);

      【讨论】:

        【解决方案5】:

        PHP 中的 OR :)

        <?php
            error_reporting(E_ALL);
            ini_set("display_errors", 1);
        
            $names = array('Chevalier','Sorcier','Archer');
            $values = array('5','6','8');
            $fusion = array();
        
            for($i=0; $i<count($names); $i++){
                $fusion[$names[$i]] = $values[$i];
            }
        
            echo '<pre>';
            print_r($names);
            print_r($values);
            print_r($fusion);
            echo '</pre>';
        ?>
        

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性的 cmets 挤满你的代码,因为这会降低代码和解释的可读性!
        猜你喜欢
        • 2016-05-10
        • 2018-09-29
        • 1970-01-01
        • 2012-01-07
        • 2014-01-23
        • 2011-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多