0

I have the following Object

let demo = {a:'b', c:{0:{id:'one'},1:{id:'two'}}, d:{0:{country: {0:{name:'mx'},1:{name:'usa'}} }} };

The keys, example (0, 1), are integrated into an array, as shown below:

let result = {a:'b', c:[{id:'one'},{id:'two'}], d:[{country:[{name:'mx'},{name:'usa'}] }] };

Any idea how to do it?

1 Answer 1

1

You can recursively reduce the object to new object, and convert each object that has the key 0 to an array using Object.values():

const demo = {a:'b', c:{0:{id:'one'},1:{id:'two'}}, d:{0:{country: {0:{name:'mx'},1:{name:'usa'}} }} };

const arrayfy = (o) => Object.entries(o)
  .reduce((r, [k, v]) => {
    if(typeof v === 'object') {
      const t = arrayfy(v);
      r[k] = '0' in v ? Object.values(t) : arrayfy(t);
    } else {
      r[k] = v;
    }
  
    return r;
  }, {});
  
const result = arrayfy(demo);

console.log(result);

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.