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

我在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);

    });

  }

}


一只甜甜圈
浏览 490回答 4
4回答

慕码人2483693

您可以使用它来删除空属性 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

开满天机

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

翻过高山走不出你

使用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'}));

慕桂英4014372

或使用Object.fromEntries(目前仅在Chrome和Firefox上受支持)function filterObject(obj) {    return Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== ""));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript