0

How do I turn the following array of objects (packageMap) into a string of names based on an array of matching id's

I am imagining it to be a combination of filter and map but I can't understand it!

    const packageMap = [
    {
      id: `g3IbvxHPGt4xUVfYK`,
      name: `Package 1 - Cost £10`
    },
    {
      id: `HPGKCapDCJS76sgd7`,
      name: `Package 2 - Cost £20`
    },
    {
      id: `jbd73hndxJH6U6j6s`,
      name: `Package 3 - Cost £1`
    },
    {
      id: `5F53DSndxJH6nns22`,
      name: `Package 3 - Cost £5`
    }
  ];

  const matchingIDs = ['5F53DSndxJH6nns22', 'HPGKCapDCJS76sgd7'];

If I can somehow get an array of names from packageMap to look like this

let packages = ['Package 3 - Cost £5', 'Package 2 - Cost £20']

I can then use join on packages

let joined = packages.join(' and ')

let outStr = `You are subscribed to ${joined}`

console.log(outStr)

// "You are subscribed to Package 3 - Cost £5 and Package 2 - Cost £20"

I am using node so not constrained by old browsers or anything like that, so latest versions of answers are fine.

0

3 Answers 3

4
packageMap.filter(({ id }) => matchingIDs.includes(id)).map(({ name }) => name)
Sign up to request clarification or add additional context in comments.

Comments

2

This would work:

const packageMap = [
  {
    id: `g3IbvxHPGt4xUVfYK`,
    name: `Package 1 - Cost £10`
  },
  {
    id: `HPGKCapDCJS76sgd7`,
    name: `Package 2 - Cost £20`
  },
  {
    id: `jbd73hndxJH6U6j6s`,
    name: `Package 3 - Cost £1`
  },
  {
    id: `5F53DSndxJH6nns22`,
    name: `Package 3 - Cost £5`
  }
];

const matchingIDs = ['5F53DSndxJH6nns22', 'HPGKCapDCJS76sgd7'];

let packages = matchingIDs.map(x => packageMap.find(y => y.id == x).name)

console.log(packages)

Comments

1

Use reduce and includes

const packageMap = [
  {
    id: `g3IbvxHPGt4xUVfYK`,
    name: `Package 1 - Cost £10`,
  },
  {
    id: `HPGKCapDCJS76sgd7`,
    name: `Package 2 - Cost £20`,
  },
  {
    id: `jbd73hndxJH6U6j6s`,
    name: `Package 3 - Cost £1`,
  },
  {
    id: `5F53DSndxJH6nns22`,
    name: `Package 3 - Cost £5`,
  },
];

const matchingIDs = ["5F53DSndxJH6nns22", "HPGKCapDCJS76sgd7"];

const names = packageMap.reduce(
  (acc, { id, name }) => (matchingIDs.includes(id) ? [...acc, name] : acc),
  []
);

console.log(names);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.