0

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,
2
  • 2
    Do you really want to get an array of little objects, each having only one property? That doesn't seem useful. Why not a single plain object with many key/value pairs? Commented Apr 28, 2022 at 20:20
  • it is because the sizes will vary, an the user will be able to select only some keys from the main array. I will need to make a comparsion between two objects, and I will filter the values later on, based on the similarity of these two objects Commented Apr 28, 2022 at 20:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.