如何防止发送空属性-object.assign

时间:2019-04-12 12:37:18

标签: javascript angular

我在Angular中具有搜索功能。我使用object.assign将参数分配给对象。但是,并非所有字段都是必需的。如果存在一个空字段,则将其作为一个空字符串发送出去。

如何仅分配具有值的属性。

export class PropertySearchComponent implements OnInit {

searchForm: FormGroup;
  searchParams: any = {};
  properties: Property;

  constructor(private advertService: AdvertService, private alertify: AlertifyService, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.createSearchForm();
  }

  createSearchForm() {
    this.searchForm = this.formBuilder.group({
      county: ['', Validators.nullValidator],
      town: ['', Validators.nullValidator],
      min_bedrooms: ['', Validators.nullValidator],
      max_bedrooms: ['', Validators.nullValidator],
      min_bathrooms: ['', Validators.nullValidator],
      max_bathrooms: ['', Validators.nullValidator],
      min_price: ['', Validators.nullValidator],
      max_price: ['', Validators.nullValidator],
      selling_type: ['', Validators.nullValidator],
      property_type: ['', Validators.nullValidator],
    });
  }

  search() {
    this.searchParams = (Object.assign({}, this.searchForm.value));
    this.advertService.propertySearch(this.searchParams).subscribe(data => {
      this.properties = data;
      this.properties.forEach(property => {
        if (property.photos) {
          property.mainPhotoUrl =  property.photos['url'];
          console.log(property.mainPhotoUrl);
        }
      });
      console.log(this.properties);
    }, error => {
      console.log(error);
    });
  }
}

3 个答案:

答案 0 :(得分:0)

您可以这样强制排除字段的值:Object.assign({}, this.searchForm.value, {town: undefined, selling_type: undefined})

答案 1 :(得分:0)

使用Object.entries并过滤掉不需要的内容,然后对它们使用reduce来构建新对象

function filterObject(obj) {
  return Object.entries(obj).filter(([key, value]) => value !== "").reduce((obj, entry) => {
    const [key, value] = entry;
    obj[key] = value;
    return obj;
  }, {});
}

console.log(filterObject({a:1, b:false, c:'', d:'something'}));

或使用Object.fromEntries(目前仅在Chrome和Firefox上受支持)

function filterObject(obj) {
    return Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== ""));
}

答案 2 :(得分:0)

您可以使用它来删除空属性Object.keys(obj).forEach(key => obj[key] == undefined || obj[key] == '' ? delete obj[key] : '');

如果仅删除未定义的属性

Object.keys(obj).forEach(key => obj[key] == undefined ? delete obj[key] : '');

您的代码更新:

 var obj = Object.assign({}, this.searchForm.value);
     Object.keys(obj).forEach(key => obj[key] == undefined || obj[key] == '' ? delete obj[key] : '');
this.searchParams = obj