如何在jQuery中向现有对象添加元素?

时间:2017-03-27 14:50:33

标签: jquery

jQuery代码:

var addproperty = {
    OwnerName: OwnerName,
    OwnerEmail: OwnerEmail,
    OwnerMobile: OwnerMobile,
    OwnerType: OwnerType,
    Propertyfor: Propertyfor,
    ProjectName: ProjectName,
    ProjectAddress: ProjectAddress,
    State: State,
    City: City,
    Area: Area,
    ProjectType: ProjectType,
    BHK: BHK,
    Bathroom: Bathroom,
    Balcony: Balcony,
    Builtup: Builtup,
    Carpet: Carpet,
    Unit: Unit,
    Furnish: Furnish
}

if(Propertyfor == 'rent'){
    $(addproperty).extend({
        RentPossessionDate: RentPossessionDate,
        MonthlyRent: MonthlyRent,
        Maintanace: Maintanace,
        SecuiryDeposit: SecuiryDeposit,
        Bachelors: Bachelors,
        RentNegotiable: RentNegotiable
});

没有使用addproperty将新元素插入现有对象。我的编码错误在哪里?

2 个答案:

答案 0 :(得分:2)

问题是因为您将addproperty对象提供给jQuery对象的构造函数。

要正确使用extend(),只需直接从jQuery对象中调用它,即$.extend(obj, newObj),如下所示:

var addproperty = {
  OwnerName: 'OwnerName',
  OwnerEmail: 'OwnerEmail',
  OwnerMobile: 'OwnerMobile',
  OwnerType: 'OwnerType',
  Propertyfor: 'Propertyfor',
  ProjectName: 'ProjectName',
  ProjectAddress: 'ProjectAddress',
  State: 'State',
  City: 'City',
  Area: 'Area',
  ProjectType: 'ProjectType',
  BHK: 'BHK',
  Bathroom: 'Bathroom',
  Balcony: 'Balcony',
  Builtup: 'Builtup',
  Carpet: 'Carpet',
  Unit: 'Unit',
  Furnish: 'Furnish'
}

var Propertyfor = 'rent';

if (Propertyfor == 'rent') {
  $.extend(addproperty, {
    RentPossessionDate: 'RentPossessionDate',
    MonthlyRent: 'MonthlyRent',
    Maintanace: 'Maintanace',
    SecuiryDeposit: 'SecuiryDeposit',
    Bachelors: 'Bachelors',
    RentNegotiable: 'RentNegotiable'
  });
}

console.log(addproperty);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

请注意,为了实现上述功能,我必须将属性值更改为字符串,因为您没有提供代码库的那部分。

答案 1 :(得分:0)

我修复了代码中的一些问题。有很多拼写错误。必须为要扩展的对象提供npm install -g create-react-app create-react-app hello-world cd hello-world npm start 函数,并提供包含所需属性的新对象。

extend

观察控制台。这是一个工作小提琴: https://jsfiddle.net/fqtaoo6s/