编写一个纯函数从内部属性返回另一个对象的一个​​对象?

时间:2018-01-30 21:02:30

标签: javascript arrays transformation reduce

进行一些数据转换练习并陷入困境。我有一个对象,我想要转换为from (starting) - > to (expected ending)输出如下所述。我尝试使用Array.reduceObject.assign来保持输出纯净。但我无法让它正常工作。

/**
 *  from (starting): {topic: {id: 2}, products: {id: 3}}
 *  to (expected ending):   {topic: 2, products: 3}
 */

const starting = {topic: {id: 2}, products: {id: 3}};

const ending = Object.keys(starting).reduce((p, key) => {
  if(!p[key]) p[key] = key;
  return Object.assign(p[key], starting[key].id);  
}, {})

4 个答案:

答案 0 :(得分:7)

您可以使用reduce,只需记住在每次迭代后返回起始对象。



function convert(start) {
  return Object.keys(starting).reduce((o, key) => {
      o[key] = start[key].id;
      return o;
    }, {});
}

const starting = {topic: {id: 2}, products: {id: 3}};
console.log(convert(starting));




答案 1 :(得分:3)

试试这个:

var starting = {topic: {id: 2}, products: {id: 3}};

var ending = Object.keys(starting).reduce((p, key) => {
  p[key] = starting[key].id;
  return p;
}, {})

这将创建一个新对象,因此不需要Object.assign等来保持输出纯净。

答案 2 :(得分:2)

我认为reduce()不是正确的工具。

尝试使用starting代替forEach()的密钥:

const starting = {topic: {id: 2}, products: {id: 3}};

const ending = {};
Object.keys(starting).forEach(p => ending[p] = starting[p].id);

console.log(ending);

答案 3 :(得分:2)

纯函数解决方案需要您在每次迭代时返回一个新对象:



function convert(start) {
  return Object.keys(starting).reduce((o, key) => 
    Object.assign({}, {
      [key]: start[key].id
    }, o), {});
}

const starting = {topic: {id: 2}, products: {id: 3}};

console.log(convert(starting));




使用对象传播使它更清洁:



function convert(start) {
  return Object.keys(starting).reduce((o, key) => ({
    ...o,
    [key]: start[key].id
  }), {});
}

const starting = {topic: {id: 2}, products: {id: 3}};

console.log(convert(starting));