简体   繁体   中英

adding an object into an array of objects with a function?

I understand the commands needed to add an object to an array. I know its array.push(object) .

However, say I have this array of objects:

 const artists = [{ "rank": 1, "name": "Rakim", "year": 1985, "album": "Paid in Full", }, { "rank": 2, "name": "Nas", "year": 1994, "album": "Illmatic" } ]

If i needed to add a new one with a function. How would I do so? And i want to make it a function that would allow me to add more than one in the future.

So something like,

function addArtist(array {}) {
  return array;
}

console.log(addArtist(array {
  new object here
}));

You need to pass an array of objects to the function and it to the initial one artists (which should be let ) using the spread operator :

 let artists = [ { "rank": 1, "name": "Rakim", "year": 1985, "album": "Paid in Full" }, { "rank": 2, "name": "Nas", "year": 1994, "album": "Illmatic" } ] function addArtist (artistsToAdd) { artists.push(...artistsToAdd); return artists; } const objects = [ { "rank": 3, "name": "Bob", "year": 1995, "album": "Album3" }, { "rank": 4, "name": "Nas", "year": 1992, "album": "Album4" } ]; console.log(addArtist(objects));

You can also use concat to add the objects in the list.

In case you want to separate your code into multiple files and you don't want to pollute your global scope with global artists variable or you have multiple variables with artists interface, you can use:

function addToArtists(artists, ...newArtists) {
  artists.push(...newArtists);
  return artists;
}

The script above modifies the array passed as the first parameter because arrays are reference types in JavaScript.

However, the function proposed above (without type checks) is pretty much general addToArray function. Therefore, from the programming style perspective I would consider to go with a more precise implementation such as:

function addArtist(artists, rank, name, year, album) {
  artists.push({rank, name, year, album});
  return artists;
}

If you only need to add a new artist one at a time - eg, from input by the user on the page, you could do:

 const artists = [{ "rank": 1, "name": "Rakim", "year": 1985, "album": "Paid in Full" }, { "rank": 2, "name": "Nas", "year": 1994, "album": "Illmatic" } ] function addNewArtist(r, n, y, a) { artists.push({"rank": r, "name": n, "year": y, "album": a}); } addNewArtist(3, "Bob", 1999, "His new one"); addNewArtist(4, "Joe", 2015, "His latest one"); console.log(artists);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM