【问题标题】:how to assign all objects in an array?如何分配数组中的所有对象?
【发布时间】:2019-11-13 13:20:39
【问题描述】:

假设我有一个这样的数组:

[ { full_name: 'Sickö' }, 
  { location: 'New York City, United States' },
  { follower: '1.2M' },
  { er: '5.59%' },
  { topics: 'Fashion' } ]

我想把它做成一个像这样的对象:

{
  fullname: 'Sicko',
  location: 'New York City, United State'
  ..and more
}

我知道我可以使用 Object.assign 组合它们,但不知道如何分配它们。

【问题讨论】:

  • 您如何知道何时移动到另一个对象,因为您的示例中的数组显示为您要创建的对象的每个属性都指定了一个对象。

标签: javascript jquery json object javascript-objects


【解决方案1】:
let all = [ { full_name: 'Sickö' }, 
  { location: 'New York City, United States' },
  { follower: '1.2M' },
  { er: '5.59%' },
  { topics: 'Fashion' } ];

let res = Object.assign({}, ...all);

【讨论】:

    【解决方案2】:

    您可以使用Array.reduce() 以等于空对象{} 的累加器开头,并在reducer 的每次迭代中使用Object.assign()。像这样的:

    const input = [
      {full_name: 'Sickö'},
      {location: 'New York City, United States'},
      {follower: '1.2M'},
      {er: '5.59%'},
      {topics: 'Fashion'}
    ];
    
    function assign(acc, obj)
    {
        return Object.assign(acc, obj);
    }
    
    let res = input.reduce(assign, {});
    console.log(res);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    但是,Object.assign() 旨在接受多个sources,因此如果您有ES6 支持,您可以将其与spread syntax 一起使用:

    const input = [
      {full_name: 'Sickö'},
      {location: 'New York City, United States'},
      {follower: '1.2M'},
      {er: '5.59%'},
      {topics: 'Fashion'}
    ];
    
    let res = Object.assign({}, ...input);
    console.log(res);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    【讨论】:

    • 当它们是数组中的多个对象时,它是如何工作的,即,不是每个对象都属于一个对象?
    【解决方案3】:

    当您标记 jquery 时,如果您需要使用相同的解决方案:

    var data = [ { full_name: 'Sickö' }, 
      { location: 'New York City, United States' },
      { follower: '1.2M' },
      { er: '5.59%' },
      { topics: 'Fashion' } ];
    
    var d = $.extend({}, ...data);
    
    console.log(d);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多