Combining or substituting elements from separate arrays when they share a common property value (javascript)

Encountering an issue with merging two objects while working with the Contentful API. The data structure for links provided by the API is separated into arrays of objects, making further processing complex due to the absence of a single object. Each object in the array is linked by an id. The objective is to merge or potentially replace these objects.

Below is the data structure:

const dataDictionary = {
  includes: {
    entry: [
      {
       fields: {data: 'https://link1.com'},
       sys: {id: 12345}
      },
      ...
    ]
  },
  items: [
    {
      fields: {
        urls: [
          {
            id: 14345,
            type: 'link'
          },
          ...
        ],
        ...
      }
    },
    ..
  ]
}

The goal is to combine and modify all arrays containing links within the items, using the actual link values from includes.

Here's the code being used:

const mergeByValue = (arrayTo, arrayFrom) => {
    const finalMerge = arrayTo.map(itm => ({
      ...arrayFrom.find((item) => (item.sys.id === itm.id) && item),
      ...itm
    }));
    return finalMerge;
}

const parseDataDictionary = (dataDictionary) => {
  const pages = dataDictionary.items;
  const includes = dataDictionary.includes.Entry;
  pages.map(page => {
   return Object.entries(page.fields).map(([key, value]) => {
     if (Object.prototype.toString.call(value) === '[object Array]') {
      return mergeByValue(value, includes);
     }
   })
  })
}

parseDataDictionary(dataDictionary);

The merging process appears to be functioning correctly, yet the expected merged values are not being returned. Any insight on resolving this issue would be greatly appreciated. Thank you!

UPD: The desired outcome:

{
 items: [
    {
      fields: {
        urls: [
          {
            id: 14345,
            type: 'link',
            data: 'https://link3.com'
          },
          ...
        ],
        ...
      }
    },
    ...
  ]
}

Answer №1

In order to correctly use the map method, you should assign the result of your mapping operation to a new variable and return that variable.


              let modifiedPages = pages.map((singlePage) => {
                return Object.entries(singlePage.fields).map(([name, property]) => {
                    if (
                        Object.prototype.toString.call(property) ===
                        "[object Array]"
                    ) {
                        return mergeByValue(property, includes);
                    }
                });
            });
            return modifiedPages;

Answer №2

Here's an alternative approach:

const dataDictionary = {includes: {entry: [{fields: {data: 'https://link1.com'},sys: {id: 12345}},{fields: {data: 'https://link2.com'},sys: {id: 16349}},{fields: {data: 'https://link3.com'},sys: {id: 14345}},{fields: {data: 'https://link4.com'},sys: {id: 98765}},{fields: {data: 'https://link5.com'},sys: {id: 43210}},]},items: [{fields: {urls: [{id: 14345,type: 'link'},{id: 16349,type: 'link'}],dataKey: 'dataPrpoperty',dataKey2: 'dataPrpoperty2',}},{fields: {urls: [{id: 12345,type: 'link'},],dataKey: 'dataPrpoperty',dataKey2: 'dataPrpoperty2',helpfulLinks: [{id: 98765,type: 'link'},{id: 43210,type: 'link'}]}},]}
          
const entryLinks = dataDictionary.includes.entry
  .reduce((acc, { sys: { id }, fields: { data } }) => ({ ...acc, [id]: data }), {})
 
const addLinks = (ids) => ids.map(e => ({ ...e, data: entryLinks[e.id] }))

const updateAray = ([key, value]) => [key, Array.isArray(value) ? addLinks(value) : value]
  
const makeFields = (fields) => Object.fromEntries(Object.entries(fields).map(updateAray))

const makeItems = (items) => items.map(item => ({ fields: makeFields(item.fields) }))

const updateItems = (items) => ({ items: makeItems(items) })
         
console.log(updateItems(dataDictionary.items))
.as-console-wrapper { max-height: 100% !important; top: 0 }

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

Load Facebook video onto webpage using ajax technology

I have a database where I store the IDs of videos from Facebook, YouTube, and Vimeo. When I load any video via Ajax, Vimeo and YouTube videos load perfectly. However, Facebook videos do not load properly. The code obtained via Ajax includes a script requir ...

The MUI Select component requires two clicks to open its menu if another Select component's menu is already open

I have been developing an application with two dropdowns (Select components) positioned next to each other, denoted as A and B. When A is open and the user intends to click on B to open it, I observed that in the default behavior of material UI, the user ...

Generating a JSON report for mocha test report using babel-cli script

Currently, I am utilizing mocha and babel-cli to execute my mocha tests with the following script: "mocha --compilers js:babel-core/register --recursive" Interestingly, when I do not use babel, I can successfully generate a JSON report using this script: ...

Having issues with ng-repeat not displaying any content

Let me describe the current situation I am facing: app.controller('ResourceController', function($scope, $sce){ var resourceData; $scope.data = ''; $scope.loadResources = function(){ $.get('con ...

Can you combine multiple items in PaperJS to move them collectively?

I'm working on a PaperJS project that involves numerous circles that can move independently. In addition to this, I would like each circle to have PointText at its center acting as a label. However, instead of having to manually animate each label ev ...

Dynamically determine the position of an object within a three.js scene

Hello, I am a beginner exploring the world of threejs. Currently, I have a scene set up with an object that can be freely moved along the XYZ Axis using TransformControls.js. My goal is to retrieve the updated X,Y,Z position coordinates of this specific ...

recreating an HTML page like a grand ballroom

Can you please advise on how to display an HTML page 10 times within the same page? For example: <html> <body> <div id='s1' name='x1' > "bla bla bla " </div> <div id='dr' name='dr' ...

Using JavaScript within PHP Functions

My JavaScript function works like this: $.msgBox({ title:"msgbox", content:"whatever" }); I am trying to use it inside a PHP Function. This is what I attempted: function MsgBox(){ echo'<script type="text/javascript ...

Is there a quick method for determining the location of an item within a flat 2D list using coordinates?

I need a concise formula to determine the flattened position of an ordered pair. Imagine a TicTacToe grid as an example. |---|---|---| | 0 | 1 | 2 | |---|---|---| | 3 | 4 | 5 | |---|---|---| | 6 | 7 | 8 | |---|---|---| If given (1, 1), how do I arrive a ...

Why is it important to have specific property names?

Here is some code and HTML for triggering a radio button. It seems to work fine without any issues, but I'm wondering if the presence of a name property is necessary. When I remove the name property, it stops working. Can someone explain why? <inp ...

Utilizing an Angular framework to access external JavaScript libraries when the document is fully

I'm incorporating a third-party JavaScript library into my .NET Core ASP Angular application. This library executes its functionality within the $(document).ready method. However, I've encountered an issue where the library's logic isn' ...

What is the best way to transfer data between functions?

I'm working on a fun Santa's game to play with my friends. The concept is simple: you enter your name, click a button, and a random name from the list will be displayed as the result. I've encountered a couple of challenges: I can succe ...

Guide on extracting unique key values from an array by utilizing a different key

I have an array containing the names of products along with their storage capacities. let products = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storag ...

Javascript - issue with accurately retrieving element offset value while scrolling

My goal is to dynamically change classes for elements based on their position during scrolling. I am trying to calculate the top offset element value and adjust the classes accordingly. Here is the function I am using: handleScroll () { const header = ...

Is there a way to determine which specific element in an array in C++ corresponds to a particular address and value?

Take for instance: int values[4] = {5, 10, 15} Suppose the memory address of values[0] is at 3000 and we know the value stored at this location is 5. With just a memory address and element value given, can we figure out the position of that element in th ...

Apply a different background color to ion-item when it is clicked

Is there a way to change the background color of an ion-item when it is clicked by a user? Any help on how to achieve this would be greatly appreciated. Here's an example code snippet: <ion-item (click)="openDetail(variant)">{{variant.Product ...

Discover the steps to release a library on npm that is compatible with both import statements and require functions

Tealium Tracker was developed in ES6 and transpiled using Babel before being released on npm. When users implement it with: import initTealiumTracker from "tealium-tracker"; everything functions as intended. However, some users prefer using require ins ...

Vue.js axios API call throwing error due to undefined property 'map'

Attempting to call a data source from a remote URL results in the error TypeError: Cannot read property 'map' of undefined. The axios method is enclosed within axios.js: ..... result = new Promise((resolve, reject) => { axios.get(url) ...

jQuery is producing an incorrect HTML string that includes `="` instead of just `"`

Currently, I am in the process of developing a math task web page and I am facing an issue with setting up dynamically generated buttons. The problem lies in my code generating '=" instead of " on the HTML page. function generateButton(id){ var b ...

Implementing a personalized filter onto the footer of an AngularJS UI Grid

After successfully creating a custom filter for my ui-grid that limits decimal numbers to two places and exporting it as a pdf using ui-grid-exporter, I encountered an issue. The filter works fine when exporting the main ui-grid but fails to apply within t ...