FCC高级编程篇之Record Collection

Record Collection

You are given a JSON object representing a part of your musical album collection. Each album has several properties and a unique id number as its key. Not all albums have complete information.
Write a function which takes an album's id (like 2548), a property prop (like "artist" or "tracks"), and a value (like "Addicted to Love") to modify the data in this collection.
If prop isn't "tracks" and value isn't empty (""), update or set the value for that record album's property.
Your function must always return the entire collection object.
There are several rules for handling incomplete data:
If prop is "tracks" but the album doesn't have a "tracks" property, create an empty array before adding the new value to the album's corresponding property.
If prop is "tracks" and value isn't empty (""), push the value onto the end of the album's existing tracks array.
If value is empty (""), delete the given prop property from the album.

对JS对象的增删改查

题目给的原始数据为

var collection = {
    "2548": {
      "album": "Slippery When Wet",
      "artist": "Bon Jovi",
      "tracks": [
        "Let It Rock",
        "You Give Love a Bad Name"
      ]
    },
    "2468": {
      "album": "1999",
      "artist": "Prince",
      "tracks": [
        "1999",
        "Little Red Corvette"
      ]
    },
    "1245": {
      "artist": "Robert Palmer",
      "tracks": [ ]
    },
    "5439": {
      "album": "ABBA Gold"
    }
};

规则有四:

  1. 如果输入属性不是tracks并且值不为空,则添加或更新专辑的属性;

  2. 当专辑没有tracks属性时,添加该属性,设置其值为空数组;

  3. 如果有tracks属性并且值不为空,则在末尾追加新值;

  4. 如果值为空,则删除该属性;

一步一步来,先处理没有值的情况:

function updateRecords(id, prop, value) {
  if (!value) {
    delete collection[id][prop];
  }

  return collection;
}

当值为空时,删除对应的属性。

然后处理属性不是tracks时的情况:

function updateRecords(id, prop, value) {
  if (!value) {
    delete collection[id][prop];
  } else if (prop !== 'tracks') {
    collection[id][prop] = value;
  }

  return collection;
}

接着处理proptracks时的情况:

  1. 当没有tracks属性时,按照题目要求,先添加其值为空数组;

  2. 添加新值;

function updateRecords(id, prop, value) {
  if (!value) {
    delete collection[id][prop];
  } else if (prop !== 'tracks') {
    collection[id][prop] = value;
  } else {
    if (!collection[id].hasOwnProperty('tracks')) {
      collection[id][prop] = [];
    }
    collection[id][prop].push(value);
  }

  return collection;
}

现在对所写代码进行测试,结果如下图所示。

Record-collection测试结果图.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,900评论 0 23
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,948评论 18 139
  • 不忘初心,方得始终 这句话最近一直停留在我的脑海里,遇到的人和事总会时刻提醒自己! 这十天我们做了什么? 保持节奏...
    张语桐阅读 602评论 1 1
  • 文/梅婷 我会幻想很多,实现的很少,我们朝着同一个方向行进,在视线里渐行渐远。你说了好多动人的情话,每...
    妍婷y阅读 542评论 0 3
  • 今天是来简书的第一天,这也是写在简书里的最开始的文字。 这周看完两部电影,《卑劣的街头》和《速度与激情7》。回想起...
    嘿妞是个什么鬼阅读 269评论 0 1