简体   繁体   English

用键将数组转换为对象

[英]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 . 好吧,这只是idsmap

 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. 如果具有对象的数组再次调用getCartesian并构建新的对象,则可以采用递归函数,该函数将所有键/值对分开并通过迭代值来构建新的笛卡尔积。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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