What is the best way to transfer an item from one object to another within the same array using javascript?

I'm dealing with an array structure like the following:

[
        {
            "ID": 227886,
            "post_author": "54"
        },
        {
            "ID": 227545,
            "post_author": "18"
        },
        {
            "ID": 229317,
            "post_author": "22"
        },
        {
            "img": "bang.jpg",
            "id": 229317
        },
        {
            "img": "other.png",
            "id": 227886
        },
        {
            "img": "name.jpg",
            "id": 227545
        }
]

My goal is to merge the objects with an "img" key into the objects whose "ID" matches the "img" object's "id" value.

The desired output should be:

[
        {
            "ID": 227886,
            "post_author": "54",
            "img": "other.png",
            "id": 227886
        },
        {
            "ID": 227545,
            "post_author": "18",
            "img": "name.jpg",
            "id": 227545
        },
        {
            "ID": 229317,
            "post_author": "22",
            "img": "bang.jpg",
            "id": 229317
        }  
]

Is there a way to merge objects within the same array based on matching "id" and "ID" values?

Answer №1

To organize the data based on either ID or id, you can utilize the reduce function and then convert the resulting object into an array using Object.values.

const arr = [ { "ID": 227886, "post_author": "54" }, { "ID": 227545, "post_author": "18" }, { "ID": 229317, "post_author": "22" }, { "img": "bang.jpg", "id": 229317 }, { "img": "other.png", "id": 227886 }, { "img": "name.jpg", "id": 227545 }];

const result = Object.values(arr.reduce((a, o)=>{
    if(o.ID){
        a[o.ID] = {...(a[o.ID] || {}),...o};
    } else {
        a[o.id] = {...(a[o.id] || {}),...o};
    };
    return a;
},{}));
console.log(result);

Answer №2

To create two separate arrays from the initial array - one containing objects with the post author and the other without:

const postAuthorList = initialArray.filter(obj => obj.hasOwnProperty('post_author'));
const nonPostAuthorList = initialArray.filter(obj => !obj.hasOwnProperty('post_author'));

Next, iterate through the postAuthorList to find the corresponding object from the nonPostAuthorList and merge them using Object.assign():

postAuthorList.forEach(postAuthor => Object.assign(postAuthor, nonPostAuthorList.find(obj => obj.id === postAuthor.ID)))

After running this code, the postAuthorList will now have the combined data. The specifics of the code may vary, but these are the general steps to follow.

Answer №3

To achieve this result, you can utilize the power of Object.assign for the elements in the b array and the map() function of the a array. Here's how you can do it:

let c = a.map((row, index) => Object.assign({}, row, b[index]));

Here is the complete code snippet:

let a = [
    {
        ID: 227886,
        post_author: "69",
    },
    {
        ID: 227545,
        post_author: "22",
    },
    {
        ID: 229317,
        post_author: "18",
    },
    {
        img: "moon.jpg",
        id: 229317,
    },
    {
        img: "sun.png",
        id: 227886,
    },
    {
        img: "star.jpg",
        id: 227545,
    },
];

let b = [
    {
        img: "sun.png",
        id: 227886,
    },
    {
        img: "star.jpg",
        id: 227545,
    },
    {
        img: "moon.jpg",
        id: 229317,
    },
];

let c = a.map((row, index) => Object.assign({}, row, b[index]));

console.log(c);

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

Incorporating an unique identification code within the input field

I have a HTML code that displays geolocation information: <span id="currentLat"></span>, <span id="currentLon"></span> When combined with JavaScript, it works perfectly. However, I am trying to display the above value in a text fi ...

Best practices for sending an object from client to server using Node.js

What is the best way to transfer a large object from client side to my node.js server? The object is currently stored in a variable within my script tags. ...

The combination of useEffect and Client component has the power to greatly

As a newcomer to React development, I've encountered a blocking error in my code that isn't being detected by Visual Studio Code. Here's the code snippet for my NavBar component: import React, { useState, useEffect } from "react"; import Ima ...

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...

Leveraging the power of Angular's ng-class directive in conjunction with d3.js on

Struggling to implement the angular ng-class directive with the d3js library within an svg element without success. HTML <div ng-controller="MainCtrl"> <div id="svgContainer"></div> <button id="swicthBtn" ng-click="switchStatus( ...

Guide to Performing Integration Tests on (AngularJS) Web Applications

I'm currently in the process of developing a Webapp that consists of two main parts: a node rest server and an angularjs client. The structure of the app is as follows: Rest Server <--> Api Module <--> Angular App At the moment, the serv ...

Node.js app not rendering ejs file despite using res.render() method, no error being thrown

I am encountering an issue where, when sending an ejs templated file as a response to a HTTP request, the HTML and CSS render properly but the Javascript does not respond. Even though the Javascript sources are linked in the head of the ejs response, the f ...

Clear SELECT After Submission

I have a jQuery script and need a function to reset the SELECT input after it has been submitted. <script> $(document).ready(function() { //elements var progressbox = $("#progressbox"); var progressbar = $("#progressbar"); var statustxt = ...

Provide solely the specified content range

While working with Node.js, my goal is to develop a video server that can serve a specific portion of a larger media file. Thanks to this gist, I have successfully created a video server and integrated it with an HTML5 video player using: <video contr ...

Challenges with pjax/ajax and handling the browser's back button

I've implemented pjax to ajaxify my menu links, which works well until I encounter an issue with the browser back button. In my JavaScript file, I have both Common Script files (to load all necessary js files when the user hits the URL) and Script fil ...

Unlock the full potential of custom authorization providers when integrating them with Supabse

Supabase user here looking to implement authorization with a third-party service that isn't on the supported list. Any suggestions on how to go about this? ...

Problematic Situation Arising from JavaScript AJAX and NVD3.JS Unresolved Object Error

I am currently in the process of developing a script that will allow me to retrieve data for my chart from an external PHP file. Initially, I attempted manually inputting the data into the chart and it worked perfectly fine. However, when I tried using A ...

The npm command encountered a permission issue when trying to install node-sass

Whenever I run the npm command on my Ubuntu system, I encounter a "permission denied" issue. sudo npm install node-sass EACCES: permission denied, access '/node_modules/node-sass' I have attempted to run the command as a root user or with sudo ...

Array filtering using one array condition and additional boolean conditions

Sorting through the carArray based on user-specified conditions. If a user selects the red checkbox, only cars with red paint will be displayed. If a user selects the green checkbox, only cars with green paint will be displayed. If both the red and green ...

What advantages can I expect for my client-rendered pages with Gatsby's Client Side Routing?

For a small site I developed, I utilized Gatsby for static content. However, for certain dynamically rendered content, I opted to employ client-only routes in Gatsby. Although I implemented a Header, Footer, and a specific font on my static site, these sa ...

Utilizing JQuery to extract the image title and render it as HTML code

I am currently facing an issue with displaying an image in my project. I want to hide the image using CSS (display: none) and instead, retrieve the value of its title attribute and display it within the parent div by utilizing JQuery. Despite knowing tha ...

Managing memory usage in Vue 2 when dealing with a high volume of data (approximately 50,000 objects)

I am in the process of creating a table view for large collections of moderately complex objects using Vue 2. The concept involves fetching anywhere from 50,000 to 100,000 rows from a database and storing them in a JavaScript cache. These rows are then dyn ...

What is the best way to convert a string to JSON format using Javascript?

I've been working on retrieving the results of a PHP query into a JavaScript object. However, I encountered an error message in the console saying Uncaught SyntaxError: Unexpected token { in JSON at position 66. I understand that this error occurs bec ...

Navigate through two distinct elements by categorizing them based on their types

After completing the frontend design, I moved on to integrating the backend and encountered an issue. If anyone can offer assistance or even a hint, it would be greatly appreciated. Visit the demo website for more insight. Initially, I hard coded the comp ...

Maximizing for-loop efficiency: the advantage of caching array length

Let's compare two variations of a loop iteration: for (var i = 0; i < nodes.length; i++) { ... } and var len = nodes.length; for (var i = 0; i < len; i++) { ... } Would the second version be faster than the first one in any way? ...