0

I want to convert the input to output with Javascript. Any help? Input can have more nested objects too.

const input = {
   a: {
     b: 22,
     c: 'hello',
   },
   e: 456
}

const output = [
    { 'a.b': 22},
    { 'a.c': 'hello' },
    { 'e': 456 }
];
2
  • Instead of giving just an input and output, could you please provide what you've tried? Commented Mar 23, 2020 at 20:08
  • what is the goal here? why do you want to do something like this? Is this just a homework / interview problem or is this for an actual system? you'd want to use recursion here and keep converting children through a tree essentially Commented Mar 23, 2020 at 20:08

2 Answers 2

1

You could create recursive function using reduce method for this.

const input = {
  a: {
    b: true,
    c: 'hi',
  },
  d: 123
}

function convert(data, prev = '') {
  return Object.entries(data).reduce((r, [k, v]) => {
    let key = prev + (prev ? '.' : '') + k;

    if (typeof v == 'object') {
      r.push(...convert(v, key))
    } else {
      r.push({ [key]: v })
    }

    return r;
  }, [])
}

const result = convert(input)
console.log(result)

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

Comments

0

// Best and Fast way to solve'

Object.entries(data).reduce((r, [k, v]) => { is slower with big json.

Benchmark

enter image description here

NO MORE OVER LOOP FOR Object.entries()

const input = { a: { b: 22, c: "hello", d: { f: 10 } }, e: 456 };
function flat(data, key = "", result = []) {
  for (let k in data) {
    if (typeof data[k] === "object") {
      flat(data[k], key + k + ".", result);
    } else result.push({ [key + k]: data[k] });
  }
  return result;
}
console.log(flat(input));

const input = { a: { b: 22, c: "hello", d: { f: 10 } }, e: 456 };
function flat(data, key = "", result = []) {
  for (let k in data) {
    if (typeof data[k] === "object") {
      flat(data[k], key + k + ".", result);
    } else result.push({ [key + k]: data[k] });
  }
  return result;
}
console.log(flat(input));

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.