我正在尝试重新格式化以下对象数组:
ON T2.ad_id = T1.ad_id
我要重新格式化:
SELECT T1.record_id,
T1.ad_id,
T1.gender,
T1.gender_view,
T1.time_entry
COALESCE(T2.submitted_by, 0) submitted_by
FROM Table1 T1
LEFT JOIN Table2 T2 ON T2.ad_id = T1.ad_id
如何重新格式化此对象数组?谢谢
答案 0 :(得分:2)
您可以使用map
遍历数组。使用reduce
将Attributes
数组汇总为一个对象。
let users = [{"Username":"test1","Attributes":[{"Name":"sub","Value":"1234"},{"Name":"email","Value":"test1@gmail.com"}]},{"Username":"test2","Attributes":[{"Name":"sub","Value":"5678"},{"Name":"email","Value":"test2@gmail.com"}]}]
let result = users.map(({Username,Attributes}) => {
let a = Attributes.reduce((c, v) => ({ ...c,[v.Name]: v.Value}), {});
a.Username = Username;
return a;
});
console.log(result);
更短版本:
let result = users.map(({Username, Attributes})=>({Username,...Attributes.reduce((c,v)=> ({...c, [v.Name]: v.Value}) ,{})}));
答案 1 :(得分:0)
一种可能的解决方案是使用Array.map()将每个原始object
映射到一个新的。在map()
内部,您可以遍历Attributes
数组,将属性添加到将要返回的新object
中。
let users =[
{
Username: "test1",
Attributes:[
{Name: "sub", Value:"1234"},
{Name:"email", Value:"test1@gmail.com"}
]
},
{
Username: "test2",
Attributes: [
{Name: "sub", Value:"5678"},
{Name:"email", Value:"test2@gmail.com"}
]
}
];
let res = users.map(({Username, Attributes}) =>
{
let newObj = {Username};
Attributes.forEach(({Name, Value}) => newObj[Name] = Value);
return newObj;
});
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 2 :(得分:0)
您可以使用for...of
遍历用户。通过Attributes
循环将具有2个属性的每个对象转换为键值对。使用Object.assign()
const users=[{Username:"test1",Attributes:[{Name:"sub",Value:"1234"},{Name:"email",Value:"test1@gmail.com"}]},{Username:"test2",Attributes:[{Name:"sub",Value:"5678"},{Name:"email",Value:"test2@gmail.com"}]}];
const output = [];
for(const { Username, Attributes } of users) {
const attributes = Attributes.map(({ Name, Value }) => ({ [Name]: Value }));
output.push(Object.assign({ Username }, ...attributes))
}
console.log(output)