AmanDeepSharma
AmanDeepSharma

Reputation: 2208

Merge keys in JSON object to return an array of merged keys and the value with Javascript

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

Upvotes: 0

Views: 39

Answers (2)

xdeepakv
xdeepakv

Reputation: 8125

// 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));

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

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)

Upvotes: 1

Related Questions