最近,我一直在学习如何从数组中检索对象,并且有相当一部分将对象数组转换为对象的单一对象,但是我无法绕过这个对象!
dataOfCars.js :
const dataOfCars = [
{
id: "car1",
owner: { license: "license001", name: "driver1" },
mechanic: [
{
id: "mechanic1",
owner: { license: "license001", name: "driver2" }
}
]
},
{
id: "car2",
owner: { license: "license021", name: "driver2" },
mechanic: []
},
{
id: "car3",
owner: { license: "license002", name: "driver2" },
mechanic: [
{
id: "mechanic1",
owner: { license: "license002", name: "driver2" }
}
]
}
];
module.exports = dataOfCars;
我知道有几个关于此的示例,但是我期望的输出是完全不同的,因为它涉及嵌套对象:
{
cars : {
idOrder : {
"car1" : {
id : "car1",
owner : "owner1",
mechanic : ["mechanic1", "mechanic2"]
},
...
},
result : ["car1", "car2", ...]
},
mechanics : {
idOrder : {
"mechanic1" : {
id : "mechanic1",
owner : "driver2",
},
...
},
result : ["mechanic1", ...]
},
owners : {
idOrder : {
"driver1" : {
license : "license001",
name: "driver1",
},
...
},
result : ["driver1", "driver2", ...]
}
}
我在“沙箱”上试了一下:https://codesandbox.io/s/old-morning-hx9m1。我使用了Object.assign({}, ...dataOfCars)
,但是它只对整个数组进行'spreads',因此仅按每个实体返回最终元素。这是 index.js 中的代码:
import dataOfCars from "./data.js";
import { normalize, schema } from "normalizr";
const ownerSchema = new schema.Entity("owners");
const mechanicSchema = new schema.Entity("mechanics", {
mechanic: ownerSchema
});
const carSchema = new schema.Entity("cars", {
owner: ownerSchema,
mechanics: [mechanicSchema]
});
/* This method somehow returns the very final element */
const objectPost = Object.assign({}, ...dataOfCars);
const normalizedPost = normalize(objectPost, carSchema);
// The normalized object returning the 2/3 expected entities
console.log(normalizedPost);
我还是ES6的新手,我很想知道这最终如何实现!感谢您的提前帮助!