提问人:Waqar Ahmad 提问时间:12/6/2021 更新时间:12/6/2021 访问量:221
使用属性映射将数据数组转换为 JSON
Converting an array of data to JSON using a property map
问:
我正在尝试使用键映射将 2d 数组转换为 json 对象。 关键映射如下所示
var keys = ['id', 'title', 'customer.id', 'customer.name', 'customer.phone.home', 'customer.phone.mobile' ];
数据是
var data = [
[1, 'Task 1', 'C1', 'Customer 1', '999', '8888'],
[2, 'Task 2', 'C2', 'Customer 2', '333', '5555']
];
输出 JSON 应为
var output = [
{
"id":1,
"title":"Task 1",
"customer":{
"id":"C1",
"name":"Customer 1",
"phone":{
"home":"999",
"mobile":"8888"
}
}
},
{
"id":2,
"title":"Task 2",
"customer":{
"id":"C2",
"name":"Customer 2",
"phone":{
"home":"333",
"mobile":"5555"
}
}
}
];
我正在尝试这样做,但我在这里不擅长递归等。谁能帮忙?
function arrToJSON(headers, data){
var output = [];
data.forEach(row, index){
var cObj = {};
headers.forEach(header, itemIndex){
var headerParts = header.split('.');
// NOt sure what to do here
}
}
}
答:
2赞
DecPK
12/6/2021
#1
您可以在 js 中使用 map
和 reduce
轻松获得结果。
createObj(acc, curr.split("."), 0, o[index]);
是递归中使用的函数,这就是您要查找的函数。
Arguments
createObj(
acc, // object in which you want to add value
curr.split("."), // send path as an array
0, // current index in path, initially zero
o[index] // value to be assigned
);
var keys = [
"id",
"title",
"customer.id",
"customer.name",
"customer.phone.home",
"customer.phone.mobile",
];
var data = [
[1, "Task 1", "C1", "Customer 1", "999", "8888"],
[2, "Task 2", "C2", "Customer 2", "333", "5555"],
];
function createObj(obj, arr, index, value) {
if (index === arr.length - 1) obj[arr[index]] = value;
else {
if (!obj[arr[index]]) obj[arr[index]] = {};
createObj(obj[arr[index]], arr, index + 1, value);
}
}
const result = data.map((o) => {
return keys.reduce((acc, curr, index) => {
createObj(acc, curr.split("."), 0, o[index]);
return acc;
}, {});
});
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
评论
1赞
Waqar Ahmad
12/6/2021
谢谢你的天才方法。我从没想过使用reduce方法。
1赞
xdeepakv
12/6/2021
#2
您可以简单地将 destructure 和 spread 运算符与 reduce 一起使用。
var data = [
[1, "Task 1", "C1", "Customer 1", "999", "8888"],
[2, "Task 2", "C2", "Customer 2", "333", "5555"],
];
const buildObject = (arr = []) => {
return arr.reduce((acc, [id, title, cid, name, home, mobile]) => {
const row = {
id,
title,
customer: { id: cid, name, phone: { home, mobile } },
};
return acc.concat(row);
}, []);
};
console.log(buildObject(data));
评论