2

I have an object includes arrays of arrays like below

objArray= { hh:[['a','b'],['c','d']],jj:[['x','y'],['z','w']]}

and what I want is here to change array to object:

convertedObject

{
  hh:[
      {id:'a', name:'b'},
      {id:'c', name:'d'}
    ],
  jj:[
      {id:'x', name:'y'},
      {id:'z', name:'w'}
    ],
}

I wrote 2 functions to do this but it needs a little change

function convertToObjects(arr) {
  return Object.values(arr).map(e => {
    return { id: e[0], name: e[1] };
  });
}

function convertChoicesToObjects(choicesArray) {
   return Object.keys(choicesArray).map((key) => (convertToObjects(choicesArray[key])));
}

const convertedObject=convertChoicesToObjects(objArray)

My function output is:

{
  0:[
      {id:'a', name:'b'},
      {id:'c', name:'d'}
    ],
  1:[
      {id:'x', name:'y'},
      {id:'z', name:'w'}
    ],
}
3
  • It needs a little change Could you be a little bit more precise, we have no idea what is wrong here. Commented Jan 30, 2020 at 13:38
  • Tried running this and I get a syntax error because it expects a ) or something in the convertChoicesToObjects function. Can you fix the error and explain more clearly what's supposed to be happening, what is actually happening and what you need help with? Commented Jan 30, 2020 at 13:40
  • Also objArray= { a:[['a','b'],['c','d']],b:[['x','y'],['z','w']]} is invalid or misleading, since it's not an array - it's missing [ and ] Commented Jan 30, 2020 at 13:40

6 Answers 6

1

iterate over keys and use map

const objArray = {"hh": [["a", "b"], ["c", "d"]], "jj": [["x", "y"], ["z", "w"]]};

const output = {};
Object.keys(objArray).forEach(key => {
  output[key] = objArray[key].map(item => ({"id": item[0], "name": item[1]}));
});
console.log(output);

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

Comments

1

You could use map and forEach methods.

objArray= { a:[['a','b'],['c','d']],b:[['x','y'],['z','w']]}
Object.keys(objArray).forEach((key) => {
  objArray[key] = objArray[key].map(([id, name]) => ({id, name}));
});

console.log(objArray);

Comments

1

The output can be acheived using a simple for...in loop and using .map() method of arrays:

const input = {
  a: [['a', 'b'], ['c', 'd']],
  b: [['x', 'y'],['z', 'w']]
};

const transform = (input) => {
  const output = {};

  for (key in input) {
    output[key] = input[key].map(([id, name]) => ({id, name}));
  }

  return output;
};

console.log(transform(input));

Comments

1

You can use reduce()

const objArray = { a:[['a','b'],['c','d']],b:[['x','y'],['z','w']]};

const data = Object.keys(objArray).reduce((prev, key) => {
   prev[key] = objArray[key].reduce((res, arr) => {
     res.push({id: arr[0], name: arr[1] });
     return res;
   }, []);
   return prev;
}, {});

console.log(data);

Comments

1

You could build new object with Object.fromEntries.

This approach uses another array for the wanted keys of the objects.

var data = { a: [['a', 'b'],['c','d']],b:[['x','y'],['z','w']]},
    keys = ['id', 'name'],
    result = Object.fromEntries(
        Object
            .entries(data)
            .map(([k, v]) => [
                k,
                v.map(a => Object.fromEntries(keys.map((k, i) => [k, a[i]])))
            ])
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You can write programs like little stories using prgm -

const myConvert = (o = {}) =>
  prgm                   // given input object, o
    ( o                  // starting with o
    , Object.entries     // get its entries
    , map (convert1)     // then map over them using convert1
    , Object.fromEntries // then make a new object
    )

const convert1 = ([ key, values ]) =>
  prgm                                        // given input key and values
    ( values                                  // starting with values
    , map (([ id, name ]) => ({ id, name }))  // map over arrays creating objs
    , r => [ key, r ]                         // then create a key/result pair
    )

const input =
  { a: [ ['a','b']
       , ['c','d']
       ]
  , b: [ ['x','y']
       , ['z','w']
       ]
  }

console.log
  ( myConvert (input)
  )

// => { ... }

To make this possible, we need -

const prgm = (x, ...fs) =>
  fs .reduce ((r, f) => f (r), x)

const map = f => xs =>
  xs .map (x => f (x))

But perhaps a better name for myConvert is objectMap. To make it generic, we will make the conversion function convert1 a parameter. And since there's no need to modify the keys of the input object, we will only call the conversion function on the object's values -

const identity = x =>
  x

const objectMap = (f = identity) => (o = {}) => 
  prgm                                 // given mapper, f, and object, o
    ( o                                // starting with o
    , Object.entries                   // get its entries
    , map (([ k, v ]) => [ k, f (v) ]) // transform each v using f
    , Object.fromEntries               // then make a new object
    )

Now using generic function objectMap, we can write myConvert as a specialization. This isolates the unique essence of your transformation and detangles it from the rest of your program -

const myConvert =
  objectMap                                  // using generic objectMap
    ( map (([ id, name ]) => ({ id, name })) // convert arrays to objects
    )

const input =
  { a: [ ['a','b']
       , ['c','d']
       ]
  , b: [ ['x','y']
       , ['z','w']
       ]
  }

console.log
  ( myConvert (input)
  )

// => { ... }

Hopefully this shows the power of thinking about your programs from different perspectives. Run the snippet below to confirm the results in your browser -

const prgm = (x, ...fs) =>
  fs .reduce ((r, f) => f (r), x)

const map = f => xs =>
  xs .map (x => f (x))

const identity = x =>
  x

const objectMap = (f = identity) => (o = {}) =>
  prgm
    ( o
    , Object.entries
    , map (([ k, v ]) => [ k, f (v) ])
    , Object.fromEntries
    )

// ---

const myConvert =
  objectMap
    ( map (([ id, name ]) => ({ id, name }))
    )

const input =
  { a: [ ['a','b']
       , ['c','d']
       ]
  , b: [ ['x','y']
       , ['z','w']
       ]
  }

console.log
  ( myConvert (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.