我试图从一个有嵌套数组的对象数组中创建一个对象数组。嵌套数组将被替换为键名,后面跟着一个点:
例如:
const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
result = ["id", "name", "obj.lower", "obj.higher"]我可以设法键入嵌套的键和值,但我似乎无法从数组中获取objs。
例如(预期结果):
const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
const newData = [{id: 5}, {name: "Something"}, {obj.lower: True}, {obj.higher: False}]我试图:
getValues = object => Object.entries(object).flatMap(([k, v]) => {
if (typeof v !== "object") {
return {[k]: v}
}
return v && typeof v === 'object' ? this.getKeys(v).map(s => `${k}.${s}`) : [k];
});我将将这些过滤后的对象数组与如下用户数据进行比较:
export const requiredKeys = {
data: {
id: null,
status: null,
summary: null,
// "updated_by.id": null,
// "updated_by.firstname": null,
// "updated_by.lastname": null,
// "updated_by.username": null,
// "updated_by.blocked": null,
// "pillars.pillarsType": null,
// "student.created_by": null,
// state: null,发布于 2022-04-28 20:27:36
您可以映射嵌套对象的键/值或对。从这个条目得到一个新的对象。
const
getEntries = object => Object
.entries(object)
.flatMap(([k, v]) => v && typeof v === 'object'
? getEntries(v).map(([l, v]) => [`${k}.${l}`, v])
: [[k, v]]
),
data = { id: 1, item: "Item 001", obj: { name: 'Nilton001', message: "Free001", obj2: { test: "test001" } } },
result = getEntries(data).map(pair => Object.fromEntries([pair]));
console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/72049753
复制相似问题