无法覆盖JavaScript对象

时间:2016-02-10 13:20:57

标签: javascript

我试图在下面的函数中覆盖profileData.timeline[i].text,但它似乎不起作用。谁能告诉我为什么会这样呢?

var profileData = [
    {
        id: 1,
        firstName: 'Philip',
        lastName: 'Yemofio',
        email: 'PhilipYemofio@email.com',
        address: "2985 Grant Avenue Old Bridge, NJ 08857",
        card: [
            {
                number: 'xxxx-0143',
                cvc: '117',
                expiryMonth: '02',
                expiryYear: '2019',
                type: 'Visa'
            },
            {
                number: 'xxxx-7284',
                cvc: '349',
                expiryMonth: '07',
                expiryYear: '2020',
                type: 'Visa'
            },
            {
                number: 'xxxx-1627',
                cvc: '755',
                expiryMonth: '10',
                expiryYear: '2019',
                type: 'Mastercard'
            }
        ],
        reputation: 3119,
        gold: 23,
        silver: 76,
        bronze: 132,
        timeline: [
            {
                type: 'favourite',
                business: 1,
                timestamp: 1455104648,
                text: '',
            },
            {
                type: 'favourite',
                business: 3,
                timestamp: 1454661898,
                text: '',
            },
            {
                type: 'badge',
                detail: 'silver',
                timestamp: 1454593008,
                text: '',
            },
            {
                type: 'badge',
                detail: 'bronze',
                timestamp: 1454271576,
                text: '',
            }
        ]   
    }
];

    getSelectedProfile: function(profileId) {
      var profileId = parseInt(profileId);
      for (var i = 0; i < profileData.length; i++) {
        var profile = profileData[i];
        if (profile.id === profileId) {

          if (profile.timeline.type === "favourite") {
            profile.timeline.text = profile.firstName + " has added " + " to his favourites."
          }

          console.log(profile.timeline)
          return profile;
        }
      }
    }

1 个答案:

答案 0 :(得分:2)

问题在于此代码

   if (profile.timeline.type === "favourite") {
        profile.timeline.text = profile.firstName + " has added " + " to his favourites."
      }

profile.timeline是一个数组,它没有texttype属性。

您需要迭代此数组并检查值

profile.timeline.forEach ( function(value){

      if (value.type === "favourite") {
        value.text = profile.firstName + " has added " + " to his favourites."
      }

} );