将对象数组转换为对象到对象

时间:2019-09-20 02:27:47

标签: javascript arrays object

我有一个函数,可以向我返回一个对象数组。如何处理数据以向我返回一个对象对象?

下面是我的示例:

const includedStates = ['NJ', 'NY'];

const withoutMap = () => {
  return {
    "NJ": {
      fill: "red",
      clickHandler: (event) => console.log('Custom handler for NJ', event.target.dataset.name)
    },
    "NY": {
      fill: "red",
      clickHandler: (event) => console.log('Custom handler for NY', event.target.dataset.name)
    }
  };
};

const withMap = () => {
  return includedStates.map(item => {
    return {
      [item]: 'red',
      clickHandler: (event) => console.log(event.target.dataset.name)
    }
  })
};

console.log('withoutMap =>', withoutMap());
console.log('withMap =>', withMap())

请咨询。我希望withMap函数向我返回noMap如何返回的数据结构。

我期望的数据结构是

{
  "NJ": {
    "fill": "red",
    "clickHandler": (event) => console.log('Custom handler for NJ', event.target.dataset.name)
  },
  "NY": {
    "fill": "red",
    "clickHandler": (event) => console.log('Custom handler for NY', event.target.dataset.name)
  }
}

3 个答案:

答案 0 :(得分:1)

一种选择是使用forEach并在迭代时构造一个对象:

const includedStates = ['NJ', 'NY'];

const withoutMap = () => {
  return {
    "NJ": {
      fill: "red",
      clickHandler: (event) => console.log('Custom handler for NJ', event.target.dataset.name)
    },
    "NY": {
      fill: "red",
      clickHandler: (event) => console.log('Custom handler for NY', event.target.dataset.name)
    }
  };
};

const withMap = () => {
  const result = {}
  includedStates.forEach(item => {
    result[item] = {
      [item]: 'red',
      clickHandler: (event) => console.log(event.target.dataset.name)
    }
  })
  
  return result;
};

console.log('withoutMap =>', withoutMap());
console.log('withMap =>', withMap())

另一种选择是使用reduce

const includedStates = ['NJ', 'NY'];

const withoutMap = () => {
  return {
    "NJ": {
      fill: "red",
      clickHandler: (event) => console.log('Custom handler for NJ', event.target.dataset.name)
    },
    "NY": {
      fill: "red",
      clickHandler: (event) => console.log('Custom handler for NY', event.target.dataset.name)
    }
  };
};

const withMap = () => {
  return includedStates.reduce((result, item) => {
    result[item] = {
      [item]: 'red',
      clickHandler: (event) => console.log(event.target.dataset.name)
    }
    return result;
  }, {})
};

console.log('withoutMap =>', withoutMap());
console.log('withMap =>', withMap())

答案 1 :(得分:0)

.map()只会映射数组本身中的元素,您应该使用.reduce()将其简化为一个对象。

const includedStates = ['NJ', 'NY'];


const withReduce = () => {
  return includedStates.reduce((result, item) => {
    result[item] = {
      fill: 'red',
      clickHandler: (event) => console.log(event.target.dataset.name)
    };
    return result;
  },{});
};

console.log('withReduce =>', withReduce())

答案 2 :(得分:0)

此解决方案使用具有动态属性名称和解构功能的def category_params params.permit(categories: [:name, :bgg_id]) end

reduce()