代码之家  ›  专栏  ›  技术社区  ›  Sayyed Dawood

Javascript中如何将索引关联数组的数组转换为逗号分隔的关联数组

  •  0
  • Sayyed Dawood  · 技术社区  · 8 年前

    我有一个索引关联数组,比如

    [
    0:{abc: 123, xyz: 456, foo: null, bar: 0}
    1:{abc: 235, xyz: 556, foo: null, bar: 0}
    ]
    

    现在如何将其转换为逗号分隔的形式

    [{abc: 123, xyz: 456, foo: null, bar: 0},{abc: 235, xyz: 556, foo: null, bar: 0}
        ]
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Nina Scholz    8 年前

    你可以使用 Object.assign 将数组作为目标对象。

    var data = { 0: { abc: 123, xyz: 456, foo: null, bar: 0 }, 1: { abc: 235, xyz: 556, foo: null, bar: 0 } },
        array = Object.assign([], data);
    
    console.log(array);

    或者只是 Object.values 如果索引不重要。

    var data = { 0: { abc: 123, xyz: 456, foo: null, bar: 0 }, 1: { abc: 235, xyz: 556, foo: null, bar: 0 } },
        array = Object.values(data);
    
    console.log(array);
        2
  •  1
  •   bthe0    8 年前

    如果第一个变量是对象而不是数组,则可以执行以下操作:

    object = Object.keys(object).map(key => object[key]);