提问人:CodeBug 提问时间:11/9/2023 最后编辑:CodeBug 更新时间:11/9/2023 访问量:44
拆分对象键值中的逗号并读取该值
split comma in the object key value and read the value
问:
我有对象数组,其中一些键值以逗号分隔 下面是示例对象,它是怎么回事
var data = [{
"id":1,
"x, y, z" :"1,2,3"
}, {
"id":2,
"x, y, z" :"10,12,153"
}, {
"id":3,
"x, y, z" :"9,8,5"
}, {
"id":4,
"x, y, z" :"14,87,13"
}]
这是预期的输出
[{
"id":1,
"x":1,
"y":2,
"z":3
},{
"id":2,
"x":10,
"y":12,
"z":153
},{
"id":3,
"x":9,
"y":8,
"z":5
},{
"id":4,
"x":14,
"y":87,
"z":13
}]
下面是我尝试过的代码,
const outputArray = data.map((item:any, index:number) => {
let commaHeaders = Object.keys(item)[index]?.split(',');
console.log(commaHeaders)
if(commaHeaders && commaHeaders.length >= 2) {
commaHeaders.map((comma) =>{
item[comma] = comma.trim();
})
}
return item
});
请注意,该函数应该是通用的,在某些情况下,我将获得 a,b,c 作为键值而不是 x,y,z 任何帮助或建议都非常有帮助!
答:
1赞
AKX
11/9/2023
#1
像这样:
function decommafy(obj) {
const newObj = {};
for (const [key, value] of Object.entries(obj)) {
if (key.includes(",") && typeof value === "string") {
const keys = key.split(",");
const values = value.split(",");
for (let i = 0; i < keys.length; i++) {
newObj[keys[i].trim()] = values[i].trim();
}
} else {
newObj[key] = value;
}
}
return newObj;
}
const result = [
{
id: 1,
"x, y, z": "1,2,3",
},
{
id: 2,
"fnef, fnerdl": "farb,forb",
"zub,zab": "zeeb,zib",
},
].map(decommafy);
console.log(result);
这不会自动将值转换为 Numbers,但您可以简单地添加该值。
评论
0赞
CodeBug
11/9/2023
谢谢伙计,这太完美了,完美地满足了需要。
1赞
Nina Scholz
11/9/2023
#2
您可以拆分所有键/值对(通过逗号和可选空格)并将有限值转换为数字。
const
data = [{ "id": 1, "x, y, z": "1,2,3" }, { "id": 2, "x, y, z": "10,12,153" }, { "id": 3, "x, y, z": "9,8,5" }, { "id": 4, "x, y, z": "14,87,13" }],
result = data.map(o => Object.fromEntries(Object
.entries(o)
.flatMap(([k, v]) => {
const
kk = k.split(/\s*,\s*/),
vv = v.toString().split(/\s*,\s*/).map(v => isFinite(v) ? +v : v);
return kk.map((k, i) => [k, vv[i]]);
})
));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
1赞
Florent M.
11/9/2023
#3
像这样的东西应该可以工作
const outputArray = data.map((item) => {
// Extract the keys of item
let keys = Object.keys(item);
// Find the key with comma
const commaKey = keys.find((key) => key.includes(','));
// Extract the properties
const commaHeaders = commaKey.split(', ');
// Extract the values
const commaValues = items[commaKey].split(', ');
// Assign the right value to the right key in item
commaHeaders.forEach((key, index) => {
item[key] = commaValues[index];
});
// Delete the original property
delete item[commaKey];
return item
});
评论
0赞
CodeBug
11/11/2023
谢谢伙计,这太简单易懂了
上一个:如何根据条件重置列中度数的累积
评论
item:any, index:number
是 Javascript 中的语法错误