【问题标题】:How to get the corresponding key and value from the object and convert it to an array object如何从对象中获取对应的key和value,并将其转换为数组对象
【发布时间】:2021-08-02 16:14:14
【问题描述】:

我提到了这篇文章,但不是我想要的convert object keys and values to an array of objects

我有以下数据:

var test = {
  apple1:"a",
  apple2: "b",
  apple3: "c",
  v1r:'1',
  v2r:'2',
  v3r:'3',
  v4r:'4',
  a1:'5'
}

我的尝试:

var keys = Object.keys(test);
var result =  keys.reduce((cur,item)=>{
   if(/^\d+$/.test(item)){
     let obj = {}
     obj[item] = test[item]
   }
   return cur
},[])

这不是我想要的。

我期待的结果如下:

let result = [{apple1:'a',v1r:'1',a1:'5'},{apple2:'b',v2r:'2'},{apple3:'c',v3r:'3'},{v4r:'4'},]

非常感谢您的帮助!

【问题讨论】:

  • 您对属于共同的财产有任何具体规定吗?你怎么知道apple1v1r属于同一个。
  • @derpirscher 嗨,它是用数字归因的
  • 如果有一个名为v12rv23r的键会发生什么
  • @brk 感谢评论,重新生成一个新对象
  • @brk 嗨,我再次编辑了问题,请再看看

标签: javascript


【解决方案1】:

一个非常基本(并且非常通用)的方法是检查属性中是否有数字,然后将值添加到相应索引处的对象中。当然,如果属性名称不符合规则,这可能会导致不良结果

var test = {
  apple1:"a",
  apple2: "b",
  apple3: "c",
  v1r:'1',
  v2r:'2',
  v3r:'3',
  v4r:'4',
  a1:'5'
}
let a = [];
for (let p of Object.keys(test)) {
  let m = p.match(/(\d+)/);
  if (!m) continue;
  var e = a[+m[1]] || {};
  e[p]  = test[p];
  a[+m[1]] = e;
}

a = a.filter(x => !!x)

console.log(a);

【讨论】:

  • 哇,这正是我需要的。非常感谢您的帮助
  • 如果key是v2errf1:'6'会失败
  • @brk 你说的失败是什么意思?它将将该属性与apple2v2r 组合在一起
  • 为什么它会与apple2v2r分组
  • 因为它按找到的第一个数字进行分组......从这个例子看来,OP 想要什么......
【解决方案2】:

每次迭代的步骤(使用Array#reduce

  1. 从密钥中获取数字
  2. 从数组中获取与数字相同索引的对象
  3. 如果对象不存在,则创建它并将其添加到数组中
  4. 将键和值添加到数组中

reduce 调用之后,您可以使用.filter(Boolean) 删除由键中的数字间隙创建的任何空值

var test = {
  apple1: "a",
  apple2: "b",
  apple3: "c",
  v1r: "1",
  v2r: "2",
  v3r: "3",
  x9y1: false
};

var result = Object.entries(test).reduce(function(result, [key, value]) {
  // Get the number (step 1)
  var index = /(\d+)[^\d]*$/.exec(key);
  if (!index || !index[1]) return result;
  index = +index[1];
  // Get the object from the array (step 2)
  var item = result[index];
  // Add it if it doesn't exist (step 3)
  if (!item) result[index] = item = {};
  // Add the key and the value (step 4)
  item[key] = value;
  return result;
}, []).filter(Boolean);

console.log(result);

编辑:如果您想获取键中的最后一个数字而不是第一个数字,则可以使用此正则表达式 /(\d+)[^\d]*$/ 代替,您还必须更改索引,因为您将访问第一个匹配的组 @ 987654327@ 而不是整个正则表达式匹配。

【讨论】:

  • @BaiClassmateXiao 很高兴能帮上忙,我已经编辑了问题,如果键中的数字超过 1 个,它只会读取最后一个(我假设这就是你想要的)
猜你喜欢
  • 2020-04-09
  • 2022-06-12
  • 2018-12-13
  • 2020-03-29
  • 2021-07-23
  • 2021-06-12
  • 2022-01-23
  • 2014-10-12
  • 2023-03-19
相关资源
最近更新 更多