本文介绍了将对象键和值转换为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的对象:
const response = {
id1-field1: true,
id1-field2: 0,
id1-field3: 3,
id2-field1: false,
id2-field2: 1,
id2-field3: 0,
id3-field1: false,
id3-field2: 0,
id3-field3: 0,
}
我需要创建一个如下所示的数组:
const formatted = [
{id: "id1", field1: true, field2: 0, field3: 3},
{id: "id2", field1: false, field2: 1, field3: 0},
{id: "id3", field1: false, field2: 0, field3: 0},
]
实现这一目标的最佳方式是什么?这就是我到目前为止的情况:
- 在数组中获取对象的键
- 用连字符分隔对象键
- 使用原始键添加对象值
const response = {
"id1-field1": true,
"id1-field2": 0,
"id1-field3": 3,
"id2-field1": false,
"id2-field2": 1,
"id2-field3": 0,
"id3-field1": false,
"id3-field2": 0,
"id3-field3": 0,
}
const keys = Object.keys(response)
const split = keys.map(x => {
return ({"oldId": x, "id": x.split('-')[0], "key": x.split('-')[1]})
})
const splitWithValues = split.map( x => {
let o = x;
o.value = response[x.oldId]
return o
})
console.log(splitWithValues)
推荐答案
使用Object#keys获取密钥,reduce放入Map。然后spreadMap#values获取数组:
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">const response = {"id1-field1":true,"id1-field2":0,"id1-field3":3,"id2-field1":false,"id2-field2":1,"id2-field3":0,"id3-field1":false,"id3-field2":0,"id3-field3":0};
const result = [...Object.keys(response)
.reduce((m, key) => {
const [id, field] = key.split('-');
const item = m.get(id) || { id };
item[field] = response[key];
return m.set(id, item);
}, new Map()).values()];
console.log(result);
这篇关于将对象键和值转换为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!