【问题标题】:How to get certain key value pairs from an array of object如何从对象数组中获取某些键值对
【发布时间】:2022-11-22 23:36:38
【问题描述】:
records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "jack55@xyz.com"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "roy@xy.com"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "jacy@x.com"}]

fields = ['id', 'email', 'last_name']

如何仅从记录中获取“id”、“email”和“last_name”,以便数据在 javascript 中看起来如下所示?

new_records = [{id: 231, email: "jack55@xyz.com", last_name: "Aston"}, {id: 232, email: "roy@xy.com", last_name: "Dillon"}, {id: 233, email: "jacy@x.com", last_name: "Wilson"}]

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    const records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "jack55@xyz.com"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "roy@xy.com"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "jacy@x.com"}]
    
    const fields = ['id', 'email', 'last_name']
    
    console.log(records.map(i=>Object.fromEntries(fields.map(f=>[f, i[f]]))))

    【讨论】:

      【解决方案2】:
      const newRecords=records.map(item=>{return {id,email,last_name}})
      

      【讨论】:

        【解决方案3】:

        您可以使用 Object.prototype.entries 将对象的键/值对更改为包含键和值的数组。

         Object.entries({ id: 231, first_name: "Jack" });
        
         // [[id, 231], ["first_name", "Jack"]];
        

        然后您可以使用它来过滤键的值并仅返回您需要的这些字段。然后你可以使用 Object.prototype.fromEntries 来反转这个过程并从键/值数组构造一个对象。

        这是一个简单的例子:

        const records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "jack55@xyz.com"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "roy@xy.com"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "jacy@x.com"}]
        
        const fields = ['id', 'email', 'last_name']
        
        const newRecords = records.map((record) => Object.fromEntries(
            Object.entries(record).filter(([key, value]) => fields.includes(key) ? [key, value] : null))
        );
        
        console.log(newRecords);

        【讨论】:

          猜你喜欢
          • 2017-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-23
          • 1970-01-01
          • 1970-01-01
          • 2022-10-13
          • 1970-01-01
          相关资源
          最近更新 更多