npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

populate-array

v1.2.0

Published

Populate an array of objects with a set of properties

Downloads

12

Readme

populate-array

Populate a key in an array of objects (Especially when working with related database results.)

Installation

npm i populate-array
# OR
yarn add populate-array

Import

// ES6:
import {populateArray} from 'populate-array';
// CommonJS:
var {populateArray} = require('populate-array');

Usage

Let's say we have an array of users where each user country is an iso2 code. We want this to be the country object instead when sending it to the client side.

import {populateArray} from "populate-array";

const users = [
    {
        id: 1,
        name: 'John Doe',
        country: 'US'
    },
    // ... and so on
];

// Normal way
for (const user of users) {
    user.country = getCountryFn(user.country)
}

// Populate way
populateArray(users, 'country', {
    each: getCountryFn
});
// Result:

[
    {
        id: 1,
        name: 'John Doe',
        country: {
            name: 'United States',
            iso2: 'US'
        }
    }
    // ... and so on
]

Arguments

The populateArray function takes three arguments:

  • array: The array of objects to populate.
  • path: The path of the objects to populate.
  • options: The options object.

Path Note: This package makes use of lodash.get to get the value of a key in an object and lodash.set to set the value of a key in an object. So nested keys are supported. e.g. user.address.city using dot notation.

Just that?

No!! ☺️ There's more to the populateArray function, and they are packed in its options.

Options

as

The name of the property to populate.

// Normal way
for (const user of users) {
  user.countryData = getCountryFn(user.country)
}

// Populate way
populateArray(users, 'country', {
  as: 'countryData',
  each: getCountryFn
});

each

A function that will be called for each object in the array. This function receives 2 arguments:

  • The path value
  • The data returned by the use function, if defined.
const users = [
  {id: 1, name: 'John Doe', country: 'US'},
  {id: 2, name: 'Jane Doe', country: 'RU'},
  {id: 3, name: 'Mark Doe', country: 'CA'},
  // ... and so on
];

populateArray(users, {
  path: 'country',
  each: (pathValue) => {
    // `pathValue` is the value of the `country` property
    // i.e either 'US', 'RU' or 'CA'
  }
});

// with `use` function
populateArray(users, {
  path: 'country',
  use(countries) {
    // `countries` is an array of the `path` values
    // i.e ['US', 'RU', 'CA']
    return getCountries(countries);
  },
  each(pathValue, useData) {
    // `pathValue` is the value of the `country` property
    // `useData` is the value returned by the `use` function
    return useData.find(country => country.iso2 === pathValue);
  }
});

unique

If true, the each function will be called only once for a unique path value object. Note: Your path value must be a string or number for this to work.

const users = [
  {id: 1, name: 'John Doe', country: 'US'},
  {id: 2, name: 'Jane Doe', country: 'RU'},
  {id: 3, name: 'Mark Doe', country: 'CA'},
  {id: 3, name: 'Jane Doe', country: 'US'},
  // ... and so on
];

populateArray(users, 'country', {
  unique: true,
  each: (pathValue) => {
    // The each function will be called only 3 times
    // because the `country` property is unique
    // i.e 'US', 'RU' and 'CA'
  }
});

use

A function that provides any data that can be used to populate.

Using a database example: A case scenario where we want to populate the userId property of a posts array.

// The `posts` array is an array of objects
// where each object has a `userId` property
// and we want to populate the `user` property
// with the user object from the database

const posts = [
  {id: 1, userId: 1, title: 'Post 1'},
  {id: 2, userId: 2, title: 'Post 2'},
  {id: 3, userId: 2, title: 'Post 3'},
  {id: 4, userId: 1, title: 'Post 4'},
]

populateArray(posts, 'userId', {
  use(userIds) {
    // `userIds` is an array of the `userId` values
    // i.e [1, 2, 2, 1]
    // Assuming we are using a mongodb like database
    return Users.find({_id: {$in: userIds}});
  },
  each(userId, users) {
    // `userId` is the value of the `userId` property
    // `users` is the value returned by the `use` function
    // now we loop through the users array and return the user object
    // that matches the `userId` value
    // This is faster/better than calling the database on each iteration.
    // in terms of performance.
    return users.find(user => user.id === userId);
  }
});

Async Operations

To run async operations in each or use functions you should make use of populateArrayAsync

import {populateArrayAsync} from "populate-array"

await populateArrayAsync(users, 'country', {
  each: getCountryFn
});