What is the best way to match object values from one key in an object with object keys that have the same values within the same object?

Utilizing TypeScript

Here is an array containing objects that needs to be transformed into a new object as shown below. (refer to the expected outcome)

// sample input array
const getPostAPI = 
[
  {
    get: '1234',
    post: 'abcd',
  },
  {
    get: '3423',
    post: 'dfcv',
  },
  // more objects omitted for brevity
]

From the given array of objects, I aim to map the post values into an array for each repeating get value. The desired result is provided below.

// expected output object
const exptectedResult = {
  '1234': ['abcd', 'iucv', 'oipl'],
  '3423': ['dfcv'],
  // more keys and values excluded for clarity
}

Below is the attempt made so far. However, some values are being overwritten. Specifically, the number of elements in the corresponding array for each get key is one less than it should be.

this.getPostMap = this.getPostAPI.reduce(
  (map, api) => ({
    ...map,
    [api.get]: map[api.get]
      ? [...map[api.get], api.post]
      : [] || [],
  }),
  {}
);

Answer №1

Executing this code snippet will ensure seamless functionality.

getPostData.reduce((accumulator, element) => {
    (accumulator[element.get] = accumulator[element.get] || []).push(element.post)
    return accumulator
}, {})

Answer №2

Wow, that code snippet looks like a jumbled mess! It could definitely be simplified for better readability. Consider this cleaner version:

const posts = [
  { get: '1234', post: 'abcd' },
  { get: '3423', post: 'dfcv' },
  { get: '1234', post: 'iucv' },
  { get: '1234', post: 'oipl' },
  { get: '3423', post: 'ffgf' },
  { get: '4567', post: 'tyui' }
];

const expectedResult = posts.reduce((map, { get, post }) => {
  map[get] = (map[get] || []).concat(post);
  return map;
}, {});

console.log(expectedResult);

Answer №3

One issue you are facing is that if the get property is undefined, you should populate it with the first post instead of leaving it empty :

this.populatePostMap = this.apiPosts.reduce(
  (map, postItem) => ({
    ...map,
    [postItem.get]: map[postItem.get]
      ? [...map[postItem.get], postItem.post]
      : [postItem.post],
  }),
  {}
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I delete cached AJAX POST requests for a web app on the iOS6 home screen?

We are currently facing a significant issue with iOS6 ajax POST request caching in our webApp. After the upgrade, most of our users who have added the app to their home screen are experiencing problems with stale data being retrieved from over 6 days ago. ...

Having trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

Conceal the sidebar menu by clicking anywhere outside of the menu bar or the designated button

I attempted to create a menu similar to the semantic UI, but so far I have only been able to click the menu button to open and close the menu. I am using a toggle class to display the sidebar, but I'm unsure if this approach is entirely correct: < ...

The Jquery ajax get method is malfunctioning

I've been trying out this code but it doesn't seem to be working. Apologies for the basic question, but I'm curious to understand why it's not functioning as expected. $(document).ready(function(){ $("button").click(function(){ ...

Code syntax error detected (scrollbar)

I am currently working on incorporating a custom content scroller found at this link into my project. I would like to adjust the scroll inertia but seem to have encountered a syntax error in the code snippet below. Could you please help me identify and c ...

Looking for a method to select a random value from an array of objects without having to go through the entire parent array?

As a JavaScript newcomer, I am seeking assistance with a particular task. The array of objects in question looks like this: const data = { "Total_packages": { "package1": { "tags": [ "kj21", ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

What is causing the issue of my button text not updating dynamically as expected within my Vue JS computed method?

Here's a brief overview of the project I'm currently working on. To maintain confidentiality, I will provide only essential information to explain the issue at hand. This project involves utilizing VUE JS. The main challenge I'm facing is u ...

When Index.html is hosted via Express, the component fails to render

Following a tutorial has led me to the end and I've made changes to my App.js as shown below: import React, { Component } from "react"; import "./App.css"; class App extends Component { render() { return ( <div> <p>lm ...

The tubular.js Youtube video background is overlapping my other components on the site, instead of displaying behind them as intended

I recently implemented the tubular.js script on my webpage to display a YouTube video as the background. On the tubular page, there is a statement that reads: First, it assumes you have a single wrapper element under the body tag that envelops all of ...

Why does npm/yarn claim that the "license" in my package.json is missing when I have it listed?

Whenever I run yarn install, a warning pops up indicating that there is no license field, despite having defined one as follows: $ jq . package.json { "name": "license-example", "version": "1.0.0", "main": "index.js", "license": "UNLICENSED", " ...

PHP's counterpart to the Javascript XMLHttpRequest

Recently, I have come across a PHP function that is quite interesting: function saveSnapshot() { header("Content-Type: application/JSON: charset=UTF-8"); global $CFG; $resString = "{\"Success\": \"True\"}"; $snapshotNa ...

Why is Vue JS throwing an error stating "undefined is not an object"?

After creating a Vue app on a single page .html file served by django, which consists of multiple components, I decided to transition this project into a full-fledged Vue.js project using the Vue CLI. Initially, I thought it would be a simple task to trans ...

Is String.substr() giving back the complete string?

Currently, I am working on an application that transforms lyrics into Google Slides by analyzing the number of line breaks between stanzas. To simplify the process, I have been repeatedly testing a specific set of lyrics. The procedure involves locating th ...

The presence of fs.existsSync as a function is not recognized when importing electron

I am currently developing a Vue and Electron application and I encountered a problem while trying to restart the application. Here is my code snippet: import { app } from 'electron'; export default { name: 'Home', methods: { re ...

The 'v-model' directive necessitates a valid attribute value for the left-hand side (LHS)

I am facing an issue with my Vue application. I have a table where each row has its own unique id. I need to show or hide certain elements based on a condition in the v-model directive which compares the row id with a value in the model. The current code s ...

When modifying v-model directly in a Vue instance, the Vuetify component on the screen may not update its displayed value

Within my Vue component example (utilizing Vue 2 and Vuetify 1), I have implemented an input field for user data entry. However, I am looking to programmatically alter the input field's data to a specific value. For instance, in this scenario, I aim ...

What could be preventing the background image from displaying properly?

I had the idea to create a game where players have to flip cards to reveal what's on the back, but I'm struggling to get the background image to display properly. As a newcomer to Vue, I'm not sure if I made a mistake somewhere. My intuition ...

Converting a string containing nested arrays into an actual array

I encountered a sample nested array string like the one below: const data = `[ { type: 'paragraph', content: 'How do I remove a particular element from an array in JavaScript?', }, { type: 'paragraph', c ...

Can we combine two arrays of objects based on their unique identifiers?

I am working with two arrays of objects: firstAry = [{ "status": "Creating", "datacenter-id": "1test", "datacenter-name": "1name" }, { "status": "Creating", ...