如何连接到索引的'数组中的对象

时间:2018-06-09 10:02:27

标签: javascript reactjs redux reducers

enter image description here我有减少器,可以更改结构[{}]或[{},{}] [0:{}]或[0:{},1:{}]

在这个改变之后我不能连接到这个原始数组。这种情况有什么解决方案吗? 我必须补充说,它真的很难改变减速器,它并没有改变阵列的结构(这是我的意见)

我添加了reducer代码:

import * as actionTypes from '../actions';
import {schema, normalize, arrayOf} from 'normalizr';
import _ from 'lodash';


const iniState = {
  recipes : []
}

function createRecipe(state = iniState, action) {
  switch (action.type) {
    case actionTypes.ADD_RECIPE:
      let newRecipe = {
        id: Math.floor(Math.random()*10000),
        re: action.payload.recipeInReducer,
        c: action.payload.compsInReducer
      }
      return {
        ...state,
        recipes: state.recipes.concat(newRecipe)
      }
      case actionTypes.EDIT_BOOLEAN:
      return {...state,
        recipes: {..._.map(state.recipes, recipe=>{
          if(recipe.id === action.payload.idFromRecipe){
            return Object.assign({}, recipe, {
              c: {..._.map(recipe.c, comp=>{
                if(comp.id === action.payload.idFromComp){
                  return {...comp,
                  toRecipe: !comp.toRecipe};
                }else{return comp}
              })
            }
            })
          } else{
            return Object.assign({}, recipe, {
              c: {..._.map(recipe.c, comp=>comp)}})
          }
        })
      }
}

 }
  return state;
}
export default createRecipe;

1 个答案:

答案 0 :(得分:1)

您可以使用Object.assign转换对象,它将键作为数组的索引。

var object = { 0: { foo: 0 }, 1: { bar: 42 } },
    array = Object.assign([], object);
    
console.log(array);