javascript - 将具有相同前缀的对象键拆分为新对象
问题描述
例如,给定一个带有键和值的对象
{
prefix_1_a: 1a,
prefix_1_b: 1b,
prefix_2_a: 2a,
prefix_2_b: 2b,
}
我想转换成两个对象:
prefix_1
带有键和值{a: 1a, b: 1b}
prefix_2
带有键和值{a: 2a, b: 2b}
另一个例子,给定一个 formData 对象:
["item_0_orange":"10",
"item_0_apple:"20",
"item_0_grape":"30",
"item_1_orange":"40",
"item_1_apple":"50",
"item_1_grape":"60",
"item_2_orange":"40",
"item_2_apple":"50",
"item_2_grape":"60"]
我想转换为 json 对象
fruitprice:
[
{key:0 ,orange:"10" , apple:"20" , grape:"30" },
{key:1 ,orange:"40" , apple:"50" , grape:"60" },
{key:2 ,orange:"40" , apple:"50" , grape:"60" }
]
- 匹配相同前缀时如何在位置下搜索和添加键和值
这是我的代码:
var fruitObject ={};
for(i=0;i<3;i++)
{
var prefix = "item_" + i;
var res = key.split("_");
var newKey = res[2];
if(key.startsWith(prefix))
{
var newObject = {};
newObject[newKey] =value;
addObject(res[1],newObject, fruitObject); //by given key
return;
};
}
解决方案
这可能是一个代价高昂的转型,但并不那么复杂:
让我们从输入开始:
const data = {
"item_0_orange": "10",
"item_0_apple": "20",
"item_0_grape": "30",
"item_1_orange": "40",
"item_1_apple": "50",
"item_1_grape": "60",
"item_2_orange": "40",
"item_2_apple": "50",
"item_2_grape": "60",
}
然后看看所需的输出:
const fruitprices = [
{
key: 0,
orange: "10",
apple: "20",
grape: "30"
},
{
key: 1,
orange: "40",
apple: "50",
grape: "60",
},
{
key: 2,
orange: "40",
apple: "50",
grape: "60",
}
]
这是从data
to的转换fruitprices
:
// this is an Object, not an Array!
const data = {
"item_0_orange": "10",
"item_0_apple": "20",
"item_0_grape": "30",
"item_1_orange": "40",
"item_1_apple": "50",
"item_1_grape": "60",
"item_2_orange": "40",
"item_2_apple": "50",
"item_2_grape": "60",
}
// transform function
const fruitprices = Object.entries(data).reduce((a, [key, val]) => {
// destructuring the key; "prefix" is not going to be used
const [prefix, outkey, fruit] = key.split('_')
// trying to find the item in the "a" Array
const item = a.find(({
key: itemkey
}) => itemkey === outkey)
if (item) { // if the key is already in the "a" Array
item[fruit] = val
} else { // if the key is not in the "a" Array yet
a.push({
key: outkey,
[fruit]: val
})
}
return a
}, [])
console.log(fruitprices)
推荐阅读
- php - PHP数组值减法直到最后一个值
- python - random.random() 在 for 循环中产生相同的结果
- android - 在 android 中使用 NDK 时崩溃,但 Firebase 不显示详细日志
- asp.net - 如何从 AssemblyInfo 中获取产品名称和产品描述?
- java - 什么是非静态变量以及如何修复它们
- bash - 如何自动终止脚本内命令的无限执行?
- servicenow - 使用 API 获取 ServiceNow 表的可用状态
- regex - 使用 word 开始搜索并在 HTML 标记上停止
- regex - 使用正则表达式获取邮政编码加上四位数
- audio - 在 php 页面上播放 base64 编码的二进制音频