如何在Javascript

时间:2018-05-24 23:05:32

标签: javascript

如何从我的其他对象创建新对象?所以我有这个代码:

var test = {
    p1: [
        'factorial',
        '11'
    ],
    p3: 'temp1',
    x1: 'factorial'
}; 

我希望得到这个:

Newobj = {
    factorial: [
        'p1',
        'x1'
    ],
    11: 'p1',
    temp1: 'p3'
} 

要解释更多:第一个对象的值将是第二个对象中的键,但是如您所见,有一个数组,我需要遍历所有值。另外,我不想重复一次。例如,factorial存在于两个键中:p1和x1因此,factorial只需要写入一次,但是包含一个包含我们得到它的数组。

谢谢!

1 个答案:

答案 0 :(得分:1)

我只是这些地图/减少问题的傻瓜。

我首先会将test 地图创建为与该值匹配的test 数组

然后将 map 缩减为普通对象,如果长度大于1则取数组值,否则只是第一个条目。

const test = {"p1":["factorial","11"],"p3":"temp1","x1":"factorial"}

// create an intermediary Map of keys and values
const newMap = Object.keys(test).reduce((map, key) => {
  // force the value to an array for consistency and iterate
  [].concat(test[key]).forEach(val => {
    // create or add to the "key" to the array at map.get(val)
    map.set(val, (map.get(val) || []).concat(key))
  })
  return map
}, new Map())

// now reduce the Map entries to a plain object
const newObj = Array.from(newMap).reduce((obj, [key, val]) => ({
  ...obj,
  [key]: val.length > 1 ? val : val[0] // only use an array if more than one entry
}), Object.create(null)) // Object.create(null) creates a plain object

console.info(newObj)

虽然有些建议......我会创建所有值数组,即使只有一个条目。这为迭代和使用对象创建了一致的API。