Can an array be transformed into an object using a function?

I am looking to convert a string into an object in JavaScript.

var api_response = { key: "settings.options.height", val: 500 };
keys = api_response.key.split('.');

var settings = { options: { height: 0 } };

I am unsure how to update the value of settings.options.height with api.val. I attempted to concatenate the array like this:

settings[keys[0]][keys[1]][keys[2]] = api.val

However, what if I have more or fewer keys than 3? Is there a function that can handle this mapping?

Answer №1

Short and sweet

api_response.key.split('.').reduceRight((obj, key) => ({ [key]: obj }), api_response.val)

Easier to understand

api_response
  .key // access key property
  .split('.') // separate by dot
  .reduceRight((obj, key) => {
     return {
       [key]: obj // create dynamic key
     };
  }, api_response.val);

The reduceRight method simplifies the array manipulation process by starting at the end instead of the beginning, using .val as the initial value for the innermost key/value pair.

Answer №2

To create this functionality, you will need to develop your own custom function, which essentially involves implementing a looping structure similar to a for loop.

var response_data = { key: "options.size.width", val: 800 };
var properties = response_data.key.split('.');
var object = {}
var pointer = object;
var lastItem = object;
for (var index = 0; index < properties.length; index++) {
  var propertyKey = properties[index]
  pointer[propertyKey] = pointer[propertyKey] || {}
  lastItem = pointer;
  pointer = pointer[propertyKey]
}
if (properties.length) {
  lastItem[properties[properties.length - 1]] = response_data.val;
}

console.log(object)

Answer №3

For those utilizing node.js, there exists a handy library designed to manage this task automatically. Additionally, it offers the ability to perform the reverse action effortlessly.

https://github.com/rhalff/dot-object-helper

Answer №4

It appears that you are looking to access a complex data structure programmatically, where the path is determined through parsing a specific syntax in a text query - using . as the delimiter. Implementing a recursive function to navigate through the data structure based on the provided path may not be too challenging. However, a key issue highlighted in your query is when the initial item in the path refers to a variable, which poses difficulties as variables cannot be directly searched within the current context; only object keys can be searched for. For instance, if the variable settings is a property of the global window object, the search should commence from the window object.

To address this, you aim to develop a method that accepts the root object (e.g., window as mentioned earlier), checks the first element of the path against properties in that object, and recursively calls itself with the resulting object along with the remaining path components.

An elementary implementation could resemble the following:


function explorePath(obj, path) {
    let [first, remaining] = path.split(".", 2);
    if (obj[first] !== undefined) {
        if (remaining.length > 0)
            return explorePath(obj[first], remaining);
        return obj[first];
    }
    return undefined;
}

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

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

Using jQuery to create a checkbox that functions like a radio button

In my code, I have a bunch of checkbox elements placed in different containers as demonstrated below: $("input:checkbox").click(function() { var url = "http://example.com/results?&" var flag = false; var $box = $(this); var $facet = $box.val ...

What could be causing my for loop to unexpectedly terminate early?

I'm currently tackling a challenge on CodeChefs: My task is to find the smallest missing positive integer in an unsorted list of numbers. Here's the code snippet I've implemented: var firstMissingPositive = function(nums) { nums.sort(); ...

Efficiently determining array inclusionLet me know if there

During a Java developer interview, I was asked the following question: Two arrays of integers are given. Print out the values from the first array that are not present in the second array. The total time complexity should be O(n). My proposed approach ...

Saving JavaScript variables to a JSON file

In my possession is a JSON file named example_json.json, which contains the following data: { "timeline": { "headline":"WELCOME", "type":"default", "text":"People say stuff", "startDate":"10/4/2011 15:02:00", ...

Contrast objects and incorporate elements that are different

In my scenario, I have a list of days where employees are scheduled to work. However, on the website, I need to display the remaining days as leave. In cases where an employee has two different shifts, there can be two elements in the object. var WorkDays ...

JavaScript Error: Unable to execute getJsonData due to function not found

I am encountering an issue with a function that retrieves JSON data from a URL Here is the code snippet: var retrieveJsonData = function(uri,callback){ $.ajax({ type: "GET", dataType: "jsonp", url: uri, jsonpCallback: 'r ...

Creating a unique filter function for a Kendo Grid that includes a multi-select column

I am facing a challenge with writing a custom filter function for a kendo grid that has multiple columns such as name, age, and city. Specifically, I need the name column to have a multiselect filter with "or" logic while the rest of the grid follows an "a ...

Mastering the art of utilizing sequelize and promises effectively

I'm currently learning how to create apps using expressJS and Sequelize. I could really use some help as I'm more accustomed to sequential programming. My project involves two models: Todo (id, title) and TodoItem (id, content, complete, todoId). ...

Tips for storing Ajax request information into separate variables

Seeking a way to store data returned from an ajax call into separate variables. Ajax Call $.ajax({ url: 'fetch_lat_lng.php', type: 'GET', dataType: "html", success: function(data) { //executed on successful response ...

Prim's method "nearest matrix"

Delving into the realm of minimum span trees and the algorithms that accompany them - Prim's, Kruskal's, and Dijkstra's algorithms has been quite enlightening. Understanding and witnessing these algorithms in action has been a fascinating j ...

Encountering the "No test cases found" error message following the update to VSCode version 1.32.1

Currently, I am utilizing jest debugging with vscode configuration. Below are the settings in my launch.json: { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Jes ...

Unable to alter the array size beyond 10000 when it comes to array operations, leading to performance discrepancies between CPU and GPU

Recently delving into OpenCL, I've run into some challenges with array additions. Utilizing the code linked below: http://code.google.com/p/opencl-book-samples/source/browse/#svn%2Ftrunk%2Fsrc%2FChapter_2%2FHelloWorld%253Fstate%253Dclosed I made mod ...

What methods can be used to adjust the dimensions of a webpage's textbox?

I've been working on a Chrome extension and I have encountered a few challenges that I need help with. One issue I'm facing is changing the size of the text box in the Facebook chat box at the right bottom corner of the page. To accomplish this ...

Display content in a specific div when the page is first loaded

I am currently working with the following code snippet: HTML: <div class="content-class"></div> JQuery Ajax: $(document).ready(function() { $(document).on("click", ".content-class", function(event) { event.preventDefault(); ...

Browserify Rails encountered an error - ParseError: Error with 'import' and 'export'. These statements can only appear with 'sourceType: module'

Recently, I encountered an issue while trying to integrate an NPM package into my Rails application. The problem I'm facing can be seen in the following image: https://i.stack.imgur.com/cIOw8.png I searched this forum for similar issues but found tha ...

Utilizing consistent form elements throughout various tabs

I'm working on an HTML project where I need to replicate form elements across different tabs with each tab having unique values. To achieve this, I found a helpful resource at . Here is what I've attempted: <html> <link rel="stylesheet" ...

Ordering and displaying data with AngularJS

Trying to maintain a constant gap of 5 between pagination elements, regardless of the total length. For instance, with $scope.itemsPerPage = 5 and total object length of 20, we should have 4 pages in pagination. However, if $scope.itemsPerPage = 2 and tota ...

Tips for utilizing JavaScript to engage with a Cisco call manager

Our team is currently working on an IVR web application built with node js. I am wondering if it is feasible to integrate with the cisco unified call manager directly through node js in our web application? ...

Issue encountered with insertion of data into database due to foreign key constraint

I have developed a complex array structure that includes the table name, column names, and values for insertion. Converting this array into an INSERT command has been successful so far. However, I encountered an issue when attempting to insert data into th ...