0

Working with Recursive function, I want to return an object with key, value. But I am returning an array with keys and values inside.

 let path = (myObj: any) => {
          if (myObj) {
            const isObject = (val: any) =>
              typeof val === 'object' && !Array.isArray(val)
            //Path Name
            const addDelimiter = (a: any, b: any) => (a ? `${a}.schema.${b}` : b)
            const paths = (obj = {}, head = '') => {
              return Object.entries(obj || {}).reduce(
                (product, [key, value]: any) => {
                  let fullPath = addDelimiter(head, key)
                  if (isObject(value)) {
                    return product.concat(paths(value, fullPath))
                  } else {
                    )
                    return product.concat({ [fullPath]: value })
                  }
                },
                []
              )
            }

returns

0: {name.schema.data: "lollololol"}
1: {name.schema.info: "John"}

I want outcome:

{
name.schema.data: "lollololol"
name.schema.info: "John"
}

1 Answer 1

1

If you don't want an array, then don't start your reducer with an array, but with a plain object, and merge using Object.assign instead of .concat:

  return Object.entries(obj || {}).reduce(
    (product, [key, value]: any) => {
      let fullPath = addDelimiter(head, key)
      if (isObject(value)) {
        // Merge objects with `.assign`, not `.concat`:
        return Object.assign(product, paths(value, fullPath));
      } else {
        return Object.assign(product, { [fullPath]: value });
      }
    },
    {} // <-- plain object instead of array
  )

Alternatively, you can also use object literal spread syntax:

      if (isObject(value)) {
        return { ...product, ...paths(value, fullPath) };
      } else {
        return { ...product, ...{ [fullPath]: value } };
      }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is exactly what I was looking for

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.