-1

I have an object as

{
    ids: ['11', '12', '13', '14'],
    cat: 1
}

I want to convert this to

[
    { id: '11', cat: 1 },
    { id: '12', cat: 1 },
    { id: '13', cat: 1 },
    { id: '14', cat: 1 }
]

Is it possible to do this single syntax? Can we use spread syntax for this?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Saravanan S
  • 1,021
  • 1
  • 10
  • 24

3 Answers3

4

Well, it's just a map over ids.

var obj = {
  ids: ['11', '12', '13', '14'],
  cat: 1
};
console.log(obj.ids.map((x) => {
  return {
    id: x,
    cat: obj.cat
  };
}));
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
0

You could take a recursive function which separates all key/value pairs and build a new cartesian product by iterating the values, if an array with objects call getCartesian again and build new objects.

The keys must have the same name as later in the result set.

function getCartesian(object) {
    return Object.entries(object).reduce((r, [k, v]) => {
        var temp = [];
        r.forEach(s =>
            (Array.isArray(v) ? v : [v]).forEach(w =>
                (w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x =>
                    temp.push(Object.assign({}, s, { [k]: x }))
                )
            )
        );
        return temp;
    }, [{}]);
}

var data = { id: ['11', '12', '13', '14'], cat: 1 };

console.log(getCartesian(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
var test = {
  ids: ['11', '12', '13', '14'],
  cat: 1
}

// one line
test.ids.map(i => { return {id: i, cat: test.cat} } )