Guide on extracting matching values from one object based on the properties of another object

Looking to iterate through the object below and extract author names based on matching titles with other objects. The goal is to create a new object for easier management.

business1

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -89.535,
                    34.3654
                ]
            },
            "place_name": "University, Mississippi, United States",
            "properties": {
                "title": "Using Adversarial Autoencoders for Multi-Modal Automatic Playlist Continuation",
                "authorTitle": "Florian Mai"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    10.14,
                    54.33
                ]
            },
            "place_name": "24105, Kiel, Schleswig-Holstein, Germany",
            "properties": {
                "title": "Using Adversarial Autoencoders for Multi-Modal Automatic Playlist Continuation",
                "authorTitle": "Iacopo Vagliano"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    10.14,
                    54.33
                ]
            },
            "place_name": "pretend place",
            "properties": {
                "title": "new title",
                "authorTitle": "joe blogs"
            }
        }

    ],
    "properties": "",
    "authors": ""
}

Desired Object (improvedObj)

var improvedObj = {

    obj1 = {
      title:'Using Adversarial Autoencoders for Multi-Modal Automatic Playlist Continuation"',
      authorList: 'Florian Mai,Iacopo Vagliano'
    },
    obj2 = {
        title:'new title',
        authorList: 'joe blogs
  }

}

Attempt at Solution

extractorArray = []

for(i=0; i<business1.features.length;i++){
extractorArray.push(business1.features[i].properties)
}
console.log('extractor', extractorArray)

var extractedValues = extractorArray.map((title) => (title));
var extractedAuthor = extractorArray.map((authorTitle) => (authorTitle))

    var improvedObj = {

      objList : {
        title:extractedValues,
        authorList: extractedAuthor
      }
    }

The code loops through each feature, extracts properties into the extractorArray, and attempts to match titles for author extraction. However, this approach does not currently achieve the desired result of linking authors to matching titles.

Answer №1

It seems that the enhanced object you are referring to is actually an array. Please correct me if I am mistaken. If so, the following code snippet should be suitable for your needs:

const authorsByBook = k.arrayOfObjects.map(obj => obj.properties).reduce((byTitle, obj) => {
    if(!byTitle[obj.title]) byTitle[obj.title] = [];
    byTitle[obj.title].push(obj.authorTitle);
return byTitle
}, {})

const updatedArray = Object.keys(authorsByBook).map(title => ({ title, authorList: authorsByBook[title].join(',')}))

The first part of the code iterates through the list and creates an object with the structure {title: authors[]}. Then, it organizes them based on titles into an array of objects {title, }.

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

What is the method for retrieving post ID with the Google Feed API?

I am currently utilizing two different JS codes to dynamically load posts from my Wordpress website: Code 1: JSON API <script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript">& ...

Caution: React is unable to identify the `PaperComponent` prop on a DOM element

Trying to create a draggable modal using Material UI's 'Modal' component. I want users to be able to move the modal around by dragging it, so I decided to use 'Draggable' from react-draggable library. However, I encountered this er ...

Having trouble sending a POST request with body parameters in Node.js? The error "undefined req.body.param" might be popping up when you're

I've encountered an issue with my server.js code: const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); var express = require('express') , http = requir ...

A PHP tag containing a div element

As someone who is new to web development, I have a question that may seem silly to some. I am familiar with adding div tags inside php tags, but I am unsure if it's possible to add onclick functions or any other type of function to these div tags. He ...

Is it advisable to prevent Set and Map from having unspecified generics in TypeScript?

Upon reviewing some old code that I wrote, I realized that I had neglected to specify a generic type for a Set. The type was set as Set<unknown>. Strangely, despite this, I found that I could still utilize all the methods of the Set without encounter ...

Using setAttribute will convert the attribute name to lowercase

When creating elements, I use the following code: var l = document.createElement("label");. I then assign attributes with l.setAttribute("formControlName","e");. However, a problem arises where the setAttribute method converts formControlName to lowercase ...

Identify when a request is being executed using AJAX by checking the URL

My current code includes multiple ajax requests from various JavaScript files. I am looking for a way to identify specific ajax requests and interrupt their execution in order to prioritize a newer one. Is it possible to detect and stop ajax requests based ...

JavaScript barcode data input

I am working with 2 inputs - #barcode and #quantity. When using a barcode scanner, I can easily enter the quantity after scanning data by pressing the Tab key. Typically, the quantity is null, indicating one piece. Currently, my cursor is in the #quantity ...

Encountering the error message "ReferenceError: parsePayload cannot be accessed before initialization"

Check out this code snippet: Experiencing an issue with 'ReferenceError: Cannot access 'parsePayload' before initialization' Any assistance would be appreciated const express = require("express"); const { createToDo, updateToD ...

Performing mathematical calculations using javascript

In my project, I'm utilizing HTML, CSS, and JavaScript to achieve the following: Dropdown menu for Category (Coffee Appliance) Dropdown menu for Product (Keurig Coffee Maker) Wattage: 1500kWh (auto-filled from Local Storage) Daily Energy Con ...

Axis incorporating additional padding for extensive domains

Encountering a peculiar issue with d3 axis generation. When creating a bottom x axis using d3.axisBottom() for ordinal domain values, extra padding is being added at the starting and ending points of ticks on the axis. This happens when the d3.scaleBand() ...

generate an object with the forEach method

When I receive data from a graphql query, my goal is to structure an object like the example below: const MY_DATA = [ { id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba', imageUrl: defaultUrl, name: 'Johann', } ...

Using environmental variables in Nuxt 3 outside of component setup scripts can be easily achieved by accessing the variables directly

I have stored different API URLs in my .env file, specifically for development and production environments. Here is how I access these URLs: const isProdEnv = process.env.NODE_ENV === 'production' const DEV_API_URL = "https://example-stage.h ...

Issue with wireframe display on video texture in three.js

Trying to apply a video texture onto a geometry in three.js using a video texture, but encountering an issue where it only displays correctly when the wireframe is set to true on the material (video shows with wireframes). When switching it to false, only ...

How can I access an InputStream from a local XML file in a PhoneGap application?

Looking for advice on how to fetch an inputstream from a local XML file using JavaScript in my PhoneGap application. I'm new to JavaScript, so any guidance would be appreciated! ...

What is the best method for embedding JSON data into a script tag within a Zope Chameleon template?

Creating a pyramid/python application where the view callable passes in an array variable called data, structured as [[[x1,y1,z1,],...],[[v1,v2,v3],...]] In the view callable: import json jsdata = json.dumps(data) I aim to place this data within a java ...

Troubling inconsistency in jQuery's .css function performance

I'm facing a problem with the jquery .css function. I am using it to retrieve the actual height of elements that have their height set to auto. The code I am currently using is as follows: $(this).css({ height: $(this).css("height"), width: $(this).c ...

Guide to incorporating HTML within React JSX following the completion of a function that yields an HTML tag

I am currently working on a function that is triggered upon submitting a Form. This function dynamically generates a paragraph based on the response received from an Axios POST request. I am facing some difficulty trying to figure out the best way to inje ...

Is it possible to navigate between jQuery EditInPlace fields using the Tab key?

Seeking advice on implementing tab functionality for a page with multiple jquery EditInPlace fields. The goal is to allow users to navigate between fields by pressing the tab key. Currently using the 'jquery-in-place-editor' plugin available at: ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...