首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用with key及其后缀从对象创建数组

使用with key及其后缀从对象创建数组
EN

Stack Overflow用户
提问于 2020-04-09 23:39:12
回答 2查看 39关注 0票数 0

在寻找使用键将对象转换/分组为数组的帮助时,键与其后缀(-)有所不同。

代码语言:javascript
复制
const obj = {
    "name-1":"a", 
    "age-1":"20", 
    "email-1":"a@email.com", 
    "name-2":"b", 
    "age-2":"24", 
    "email-2":"b@email.com", 
    "name-3":"c", 
    "age-3":"22", 
    "email-3":"c@email1.com"
};

预期结果

代码语言:javascript
复制
[
    {
        "name":"a", 
        "age":"20", 
        "email":"a@email.com"
    },
    {
        "name":"b", 
        "age":"24", 
        "email":"b@email.com"
    },
    {
        "name":"c", 
        "age":"22", 
        "email":"c@email.com"
    }
]

可能由于错误的搜索关键字无法找到重复的问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-04-09 23:53:38

您可以在Object.entries上运行一个reduce,并通过'-'拆分键,比如name-1, age-2等,然后返回一个对象数组。

代码语言:javascript
复制
const obj = {
    "name-1":"a", 
    "age-1":"20", 
    "email-1":"a@email.com", 
    "name-2":"b", 
    "age-2":"24", 
    "email-2":"b@email.com", 
    "name-3":"c", 
    "age-3":"22", 
    "email-3":"c@email1.com"
};

const res = Object.entries(obj).reduce((acc, [key, value]) => {
  const [ k, i ] = key.split('-');
  acc[i - 1] = acc[i - 1] || {};
  acc[i-1][k] = value;
  return acc;
}, [])

console.log(res);

在上面的reduce代码中,我将key拆分为'-',它给出了一个对象的键和最后一个数组的索引。

然后检查数组中是否存在索引i - 1。如果不是,则由一个空对象初始化它。这里我使用i - 1,因为给定的对象键从1开始,而数组从0开始。

最后,我将对象值放入新创建的对象中。

票数 1
EN

Stack Overflow用户

发布于 2020-04-09 23:58:38

这是一个很好的算法问题,我将用ES6语法来解决它。

多亏了一些函数,比如Object.entriesreduce,你就可以做到这一点

示例:

代码语言:javascript
复制
const obj = {
    "name-1":"a", 
    "age-1":"20", 
    "email-1":"a@email.com", 
    "name-2":"b", 
    "age-2":"24", 
    "email-2":"b@email.com", 
    "name-3":"c", 
    "age-3":"22", 
    "email-3":"c@email1.com"
};

const result = Object.entries(obj)
  // Here we destructure the entry with on the left the key, and value on the right
  .reduce((accumulator, [key, value]) => {
    const [property, index] = key.split('-');
    
    // Get the value currently being filled, or an empty object if it doesn't
    // exist yet.
    const entry = accumulator[index] || {};

    accumulator[index] = {
      // Spread the current entry to which we are adding
      // the property to the object being filled
      ...entry,
      // Dynamic key syntax
      [property]: value,
    };

    return accumulator;
  }, [])
  // Remove "holes" from the array since it's indexed with given keys
  .filter(value => value !== undefined);

console.log(result);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61124851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档