Javascript - combining properties using "concatenation"

I'm currently pulling data from JSON for a three.js scene.

My goal now is to transform data such as "position.x : 1" into object[ position ] [ x ] = 1.

The syntax object [ key ] = value isn't effective in this case. This would result in object[ position.x ] = 1, which is not what I want.

How can I achieve this transformation, or what is the name for this type of procedure?

Thank you.

Answer №1

Unfortunately, there isn't a predefined function for that specific task.

However, numerous third-party modules can assist in achieving the desired outcome.

One such module is lodash, which offers the convenient _.set method. You can access the documentation here. Alternatively, you have the option to utilize the standalone lodash.set package without including the entire lodash library.

Here's an example from the official docs:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4

_.set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5

If _.set doesn't align with your preference, there are several alternative options available through libraries like dot-prop, set-value, object-path, and dot-object.

Answer №2

If you want to achieve something similar, you could follow these steps:

let str = "size.width : 100";
let arr = str.split(/\.|\:/);   // split the string into an array using '.' and ':'
let resultObj = {};             // final object

function createObject(arr) {
    resultObj[arr[0].trim()] = {};
    resultObj[arr[0].trim()][arr[1].trim()] = arr[2].trim();
}

createObject(arr);              // call the function with the array of values
console.log(resultObj);         // display the entire resulting object
console.log(resultObj['size']['width']); // display obj['size']['width']

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

Finding the dynamic width of a div using JavaScript

I have two divs named demo1 and demo2. I want the width of demo2 to automatically adjust when I drag demo1 left to right or right to left. <div class="wrapper"> <div class="demo"></div> <div class="demo2"&g ...

Chrome experiencing conflicts with backstretch when using multiple background images

In order to dynamically apply fullscreen background images in a WordPress site, I am utilizing Backstretch.js along with a custom field. Everything is functioning properly for the body's background image. However, there seems to be an issue with anot ...

Securely verifying secret and payload with HMAC in Symfony version 5.4

My current JavaScript code is executing a POST API call to my designated endpoint: const payload = { course: args, recipient: roomId }; const signature = this.calculateSignature(JSON.stringify(payload), secret); const response = await fetch(`https:/ ...

Transform a 2-dimensional array of numbers into an array of objects labeled with a "row" index

Today my brain seems to be in full-on "fart" mode. Struggling to find a clean solution for this task without resorting to an ugly loop or recursion. I have a 2D array of numbers that looks like this: const layoutMatrix = [ 1, [1], [0.5, 0.5], [0.2 ...

Unable to obtain the vertices of the extremities due to the absence of labels on AxisHelper

My goal is to add labels on AxisHelper in Three.js that rotate along with it. I came across a helpful code snippet from this source: // Axes axes2 = new THREE.AxisHelper(70); // Axes labels addLabelAxes(); // Add axes to zoomScene zoomScene.add(axes2); ...

Displaying JSON with AngularJS HTTP Get request won't work in my project

As I delve into the world of AngularJS, I find myself caught up in a puzzle that has consumed my entire evening. My goal is to fetch JSON data from a random generator and display it in the view using a service. While {{ main.title }} seems to be working ju ...

Avoid having to refresh the page on create-react-app after uploading an image or file

Currently, my application is set up with 'create-react-app' and I am retrieving images from a folder within the 'src' directory. However, when a new image is uploaded through a form submission, it causes the page to reload as the image ...

NodeJS error: The 'error' event was not properly handled, resulting in a throw er

I've developed a basic web application using React, node-postgres, expressJS, and PostgreSQL DB. The app includes two input fields and a button. Upon clicking the button, the values are saved in the database. While running the ExpressJS server with ...

Is there a way to access the Chrome Extension popup using a keyboard shortcut?

While it is not possible to directly open a Chrome extension popup from background JavaScript, is there a method where the popup could be triggered when a user presses a specific key combination? ...

JavaScript tool for implementing sorting features on an HTML table

I am facing an issue with my AJAX-loaded table where I need sorting functionality implemented. Despite searching for various JavaScript plugins, none seem to work efficiently due to slow performance or errors. The structure of my HTML table is unique with ...

Tips for analyzing a JSON response from a meme API using HTML and JavaScript

I'm looking to integrate an API into my website in order to fetch random memes from reddit. The API was developed by D3vd and can be found on github at When I make a request to (the api), the response typically looks like this: { "postLink ...

Is it possible for the $.post function to overwrite variables within the parent function?

Recently, I delved into the world of JavaScript and my understanding is quite limited at this point. So, please bear with me as I learn :-) I am working on a basic booking system that saves dates and user IDs in MySQL. The system checks if a particular da ...

What steps should I follow to enable a tooltip in this specific situation using qtip?

In my database, I have tables for venues, venue types, and map icons with the following relationships: A venue belongs to a venue type A venue type belongs to a map icon Each venue result is shown on the index page as a partial. Each partial ...

Calculating the number of days left within a month using dayjs

Currently, I'm facing a challenge that seems to have no easy online solution, and if there's one thing I find particularly frustrating; it's dealing with dates. My current task involves calculating a person's age in months and days. Fo ...

JQuery - Receive an error message when a value is missing

With my Website almost complete, I just need to add an error message for when a movie isn't found. I have an API that returns JSON and if someone enters an invalid movie like "ifeahaef," it returns null. Is there a way to use Jquery to display an erro ...

Bidirectional binding of form input directive using isolated scope

Currently, I am diving deep into AngularJS and focusing on mastering directives. My goal is to create a form input directive that can be easily reused across all my forms, simplifying the repetitive markup that comes with each form. However, I am facing a ...

Pass the outcome back to the calling function

I've been struggling with this issue for a while. I am working with ion-autocomplete and trying to retrieve data using a factory. The Factory I'm using is as follows: myApp.factory('items', function($http){ return { list: fun ...

Try utilizing querySelectorAll() to target the second item in the list

As I delve into the world of HTML and JS, I came across the document.querySelectorAll() API. It allows me to target document.querySelectorAll('#example-container li:first-child'); to select the first child within a list with the ID 'exampl ...

Issues regarding innerHTML

I have a collapsed table with a link that collapses its content. My goal is to change the link (such as from "+" to "-" and vice versa) using JavaScript. I was able to achieve this, but now my table no longer collapses. Here is the code snippet: <div c ...

Reactjs encountered a problem with the click event

I seem to be facing a small issue with my react component code. I can't seem to figure out what's wrong. Here's the component code: import React, { Component, PropTypes } from 'react'; import styles from './Menu.css'; im ...