简体   繁体   中英

Creating an array of objects from arrays of nested objects

I'm trying to create an array of objects from an array of objects in which has nested arrays. The nested arrays are going to be subsituted for the key name followed by a dot:
for example:

const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
result = ["id", "name", "obj.lower", "obj.higher"]

I could manage to key the nested keys and values, but I can't seem to get the objs from the array.
For example (expected result):

const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
const newData = [{id: 5}, {name: "Something"}, {obj.lower: True}, {obj.higher: False}]

I have attempted:

 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];
  });

I will be comparing these filtered array of objects with a user data that seems like this:

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,

You could map the key/values or the pairs of the nested objects. From this entries get a new objects.

 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM