【问题标题】:What is the ideal way to transform an object into an array holding multiple objects in Javascript? (ES6 allowed)在Javascript中将对象转换为包含多个对象的数组的理想方法是什么? (允许 ES6)
【发布时间】:2018-12-28 23:28:01
【问题描述】:

我有一个像这样的对象:

foo: {
  someGuid: someString,
  someGuid: someString,
  someGuid: someString
}

我正在尝试找出将其作为 id/value 对的对象数组插入现有对象的最佳方法:

bar: {
  someOtherInfo: someOtherValue,
  someOtherInfo: someOtherValue,
  baz: [
    {
      id: someGuid,
      value: someString
    },
    {
      id: someGuid,
      value: someString
    },
    {
      id: someGuid,
      value: someString
    }
  ]
}

我真的很想找出实现这一目标的最佳方法。我所说的“最佳”是指代码清晰性/简单性和性能(或以上所有如果可能的话)之间的良好平衡。

我知道有多种方法可以转换这些数据,所以我真的很好奇其他人想出了什么,我觉得这对我自己和其他人来说都是一个很好的学习机会。

此外,这是在 Vue 应用程序中,如果这有所作为的话。 (我不认为有特定于 vue 的方法来做到这一点,但如果有的话,我绝对有兴趣了解如何!)


到目前为止,我想出的方法还没有奏效,但这里是为那些感兴趣的人准备的。我相信我做错了(可能过于复杂)。

我的数据:

originalObject: {
  someGuid: someString,
  someGuid: someString,
  someGuid: someString
}

newObject: {
        some: null,
        other: '1',
        stuff: null,
        irrelevant: null,
        toThis: null,
        problem: null,
        targetArray: [
          {},
        ],
      },

我的逻辑:

someFunction() {
  const foo = this.originalObject;
  const bar = this.newObject.targetArray;
  const fooLength = Object.keys(foo).length;

  Object.keys(foo).forEach(function (key) {
    for (let i = 0; i < fooLength; i++) {
      const foobar = bar[i];
      console.log(foobar.ItemAttributeId);
      console.log(foobar.Value);
      foobar.ItemAttributeId = key;
      foobar.Value = foo[key];

      bar.push({ ItemAttributeId: foobar.ItemAttributeId, Value: foobar.Value });
    }
  });
},

所以我觉得我让这变得比它需要的更复杂。此外,结果输出不正确(我以某种方式多次返回该值,但它似乎是一个随机的倍数……有时它返回 4 次,有时返回 3 次,我试图解释为什么会这样)。我觉得有一个更好的开始方式,但我错过了,现在我陷入了困境。

【问题讨论】:

  • “我知道有多种方法可以转换这些数据” - 你想出了哪些方法?到目前为止,您完成了什么,您要解决的具体问题是什么?给minimal reproducible example。对您而言,究竟什么是“良好的平衡”?对我来说,这里的“良好的学习机会”是你自己想办法的。
  • Object.entries.map 那个?
  • Object.keys().map(),无论哪种方式,某种形式的transform object to array and return a new object for every property of the foo object
  • 附带说明... 一个相当常见的模式是 [to|from}pairs 函数将对象转换为数组数组:[[someGuid, someString], [someGuid, someString], [someGuid, someString]]
  • 另请参阅your last effort - SO 不是代码编写服务,作为高级开发人员,您至少应该能够展示此类问题的当前实现并描述好的外观。

标签: javascript arrays vue.js ecmascript-6


【解决方案1】:

在 Vue 中,您将使用计算属性。

console.clear()

new Vue({
  el: "#app",
  data:{
    foo: {
      someGuid1: "someString",
      someGuid2: "someString",
      someGuid3: "someString"
    }
  },
  computed: {
    baz(){
      // nothing special here-- just javascript
      return Object.entries(this.foo).map(([key,val]) => ({id: key, value: val}))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
  {{baz}}
</div>

要将数组添加到其他对象:

console.clear()

new Vue({
  el: "#app",
  data:{
    foo: {
      someGuid1: "someString",
      someGuid2: "someString",
      someGuid3: "someString"
    }
  },
  computed: {
    bar(){
      // nothing special here-- just javascript
      return {
        some: "other",
        props: "that don't matter",
        baz: Object.entries(this.foo).map(([key,val]) => ({id: key, value: val}))
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<pre>
  {{bar}}
<pre>
</div>

【讨论】:

    【解决方案2】:

    您可以将Array.reduceObject.keys 一起使用:

    this.newObject.targetArray = Object.keys(this.originalObject).reduce((array, key) => {
      array.push({
        id: key,
        value: this.originalObject[key],
      })
    
      return array
    },[])
    

    【讨论】:

      【解决方案3】:

      我相信有两种“流行”的方式来做到这一点。

      // You have this
      const input = {
          foo: {
              someGuid1: "someString1",
              someGuid2: "someString2",
              someGuid3: "someString3"
          }
      }
      
      // You want this:
      [
          {id: "someGuid1", value: "someString1"},
          {id: "someGuid2", value: "someString2"},
          {id: "someGuid3", value: "someString3"}
      ];
      

      命令式:

      const baz = [];
      
      for (const [id, value] of Object.entries(input.foo)) {
          baz.push({ id, value });
      }
      

      功能方式:

      const baz = Object.entries(input.foo).map(([id, value]) => ({ id, value }));
      

      在我看来,你应该始终遵循你正在使用的代码库的风格,如果有的话,或者如果没有现有的代码,你会觉得更舒服。

      【讨论】:

        猜你喜欢
        • 2022-06-18
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 2011-10-14
        • 2019-03-05
        • 1970-01-01
        • 1970-01-01
        • 2015-01-03
        相关资源
        最近更新 更多