JS函数迭代对象并打印值

时间:2016-10-26 21:45:25

标签: javascript object

所以,我有一个对象。

 var library = {
    tracks: { t01: { id: "t01",
               name: "Code Monkey",
               artist: "Jonathan Coulton",
               album: "Thing a Week Three" },
          t02: { id: "t02",
               name: "Model View Controller",
               artist: "James Dempsey",
               album: "WWDC 2003"},
          t03: { id: "t03",
               name: "Four Thirty-Three",
               artist: "John Cage",
               album: "Woodstock 1952"}
            }

  }

我想迭代它并返回一些对象的属性。结果应该是:

t01: Code Monkey by Jonathan Coulton (Thing a Week Three)
t02: Model View Controller by James Dempsey (WWDC 2003)
t03: Four Thirty-Three by John Cage (Woodstock 1952)

我已经完成了以下操作 - 它返回了所需的结果 - 但练习要求我使用函数来解决这个问题(var printTracks = function(){}) - 我不知道该怎么做。

我的解决方案:

var tracks = library.tracks;
var result = Object.keys(tracks).forEach(function(t) {
  var str = t + ': ' + tracks[t].name + ' by ' + tracks[t].artist + '     
  (' + tracks[t].album + ')';
  console.log(str)
 })

感谢有关如何将我的代码转换为函数的任何想法。

3 个答案:

答案 0 :(得分:0)

它可以像一个函数一样简单,它将属性对象作为参数,并在执行所需的任何解析/格式化后返回字符串。你基本上已经有了逻辑,但如果你把它包装在一个函数中,你可以在需要的地方重用它。这是一个小改动,以便您构建一个result变量,以便您可以在最后返回它。我还在每行的末尾添加了\n个换行符。

var library = {
  tracks: {
    t01: {
      id: "t01",
      name: "Code Monkey",
      artist: "Jonathan Coulton",
      album: "Thing a Week Three"
    },
    t02: {
      id: "t02",
      name: "Model View Controller",
      artist: "James Dempsey",
      album: "WWDC 2003"
    },
    t03: {
      id: "t03",
      name: "Four Thirty-Three",
      artist: "John Cage",
      album: "Woodstock 1952"
    }
  }
};

var printTracks = function (library) {
  var tracks = library.tracks;
  var result = '';
  Object.keys(tracks).forEach(function (t) {
    result += t + ': ' + tracks[t].name + ' by ' + tracks[t].artist + ' (' + tracks[t].album + ')\n';
  });
  return result;
}

console.log(printTracks(library));

答案 1 :(得分:0)

您的解决方案输出一个字符串。输出看起来像

key1: value1
key2: value2

看起来像object {}。所以,我认为输出应该是一个对象。

function及其arguments可以概括

function f(value) { // value is an argument
  console.log(value);
}

var v = "This is something you can change"; // CHANGEABLE

f(v);

总计:

var library = {
  tracks: {
    t01: {
      id: "t01",
      name: "Code Monkey",
      artist: "Jonathan Coulton",
      album: "Thing a Week Three"
    },
    t02: {
      id: "t02",
      name: "Model View Controller",
      artist: "James Dempsey",
      album: "WWDC 2003"
    },
    t03: {
      id: "t03",
      name: "Four Thirty-Three",
      artist: "John Cage",
      album: "Woodstock 1952"
    }
  }
}

var tracks = library.tracks;

function makeCustomObj(obj) { // The argument is obj
  var res = {};
  Object.keys(obj).forEach(el => {
    res[el] = obj[el].name + " by " + obj[el].artist;
  });
  return res;
}

var r = makeCustomObj(tracks);
console.log(r);

答案 2 :(得分:0)

您可能需要一个字符串数组(如您的示例中所示)或键和文本对象(两个示例都显示)。 鉴于您的库对象:

function buildTracksArray(object) {
    var tracks = [];
    for (var k in object) {
        var track = object[k];
        tracks.push(track.id+': '+track.name+' by '+track.artist+' ('+track.album+')');
    }
    return tracks; // Returns array of strings.
}

var tracksArray = buildTracksArray(library.tracks);
console.log(tracksArray);
/* Output:
    [
        "t01: Code Monkey by Jonathan Coulton (Thing a Week Three)",
        "t02: Model View Controller by James Dempsey (WWDC 2003)",
        "t03: Four Thirty-Three by John Cage (Woodstock 1952)"
    ]
 */

function buildTracksObject(object) {
    var tracks = {};
    for (var k in object) {
        var track = object[k];
        tracks[track.id] = track.name+' by '+track.artist+' ('+track.album+')';
    }
    return tracks; // Returns object of keys and strings.
}

var tracksObject = buildTracksObject(library.tracks);
console.log(tracksObject);
/* Output:
    {
        t01: "Code Monkey by Jonathan Coulton (Thing a Week Three)",
        t02: "Model View Controller by James Dempsey (WWDC 2003)",
        t03: "Four Thirty-Three by John Cage (Woodstock 1952)"
    }
 */