简体   繁体   中英

Convert array to object with key

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM