如何使用地图和过滤器修改原始数组

时间:2020-06-08 04:48:46

标签: javascript arrays

我有一个具有这种结构的对象

const values = {
    containerName: "test",
    models: [
        {
            modelName: "1",
            modelType: "DecisionTreeClassification",
            parameters: [empty, 1, 1]
        },
        {
            modelName: "2",
            modelType: "DecisionTreeClassification",
            parameters: [empty, empty, 2, 2]
        }
    ]
    numberOfSteps: "1"
}

我想从参数数组中删除所有空项目。

我想做这样的事情

values.models.map(model => model.parameters.filter(param => param))

但我不想让它返回新数组,而是希望它修改我的原始数组。

我希望我的最终结果是

const values = {
    containerName: "test",
    models: [
        {
            modelName: "1",
            modelType: "DecisionTreeClassification",
            parameters: [1, 1]
        },
        {
            modelName: "2",
            modelType: "DecisionTreeClassification",
            parameters: [2, 2]
        }
    ]
    numberOfSteps: "1"
}

2 个答案:

答案 0 :(得分:0)

if you really want to mutate , you can use foreach

const values = {
    containerName: "test",
    models: [
        {
            modelName: "1",
            modelType: "DecisionTreeClassification",
            parameters: ['', 1, 1]
        },
        {
            modelName: "2",
            modelType: "DecisionTreeClassification",
            parameters: ['', '', 2, 2]
        }
    ],
    numberOfSteps: "1"
};

values.models.forEach((mod) => {
    mod.parameters =  mod.parameters.filter(parameter=>parameter)
    
 });

console.log(values);

答案 1 :(得分:0)

const val = {
    containerName: "test",
    models: [
        {
            modelName: "1",
            modelType: "DecisionTreeClassification",
            parameters: ['empty', 1, 1]
        },
        {
            modelName: "2",
            modelType: "DecisionTreeClassification",
            parameters: ['empty', 'empty', 2, 2]
        }
    ],
    numberOfSteps: "1"
}


  for(let [key , value] of Object.entries(val)){
      if(key=='models')
      value.forEach(x => {
          for(let i=0;i<x.parameters.length;i++)
          x.parameters.forEach(y=>{
              if(y=='empty') 
              x.parameters.shift()
          })
      });
  }
  console.log(val.models[0].parameters)
  console.log(val.models[1].parameters)