Combining keys array and values array to create an object in JavaScript

I currently have the following arrays:

var keys = [ "color", "size" ];
var values = [ "blue", "medium" ];

My goal is to transform them into an object like this:

{ color: "blue", size: "medium" }

In Python, you can achieve this easily with dict(zip(keys,values)). Is there a similar method in jQuery or vanilla JavaScript, or do I need to take the longer route?

Answer №1

Here is a concise ES6 one-liner solution that leverages Array reduce:

const properties = ['color', 'size'];
const values = ['red', 'large'];
const combined = properties.reduce((object, property, index) => ({ ...object, [property]: values[index] }), {});

console.log(combined);

Answer №2

A simple JavaScript function may look like this:

function createObject(keys, values) {
    var obj = {};
    for (var i = 0; i < keys.length; i++)
         obj[keys[i]] = values[i];
    return obj;
}

Additionally, it is worth mentioning that in JavaScript, you can easily implement functions such as zip using higher order types, which brings some functional programming concepts into the language!

Answer №4

Looking at a different approach that hasn't been mentioned yet, I believe:

const properties = ["color", "font-size"];
const styles = ["red", "16px"];
const output = {};

properties.forEach((property, index) => output[property] = styles[index]);
console.log(output);

Answer №5

To merge two arrays together, you can utilize the map method first and then transform them into an object using Object.fromEntries.

var categories = ["fruit", "vegetable"];
var values = ["apple", "carrot"];

var combinedArray = categories.map((category, index) => {
  return [categories[index], values[index]];
});
// → [["fruit", "apple"], ["vegetable", "carrot"]]

var mergedObject = Object.fromEntries(combinedArray);
// → {fruit: "apple", vegetable: "carrot"}
console.log(mergedObject);

Answer №6

Implementing a functional approach while prioritizing immutability:

const createZipObject = keys => values => keys.reduce((obj, key, index) => ({ ...obj, [key]: values[index] }), {})

const keysArray = ['apple', 'banana', 'cherry', 'date']
const valuesArray = ['elephant', 'flamingo', 'giraffe', 'hippopotamus']

const customObject = createZipObject(keysArray)(valuesArray)

console.log(customObject)

Answer №7

To convert key-value pairs into an object, you can utilize the reduce() method.

/**
 * Creates a new object from parallel arrays of keys and values.
 *
 * @param   {string[]} keys      - Array of keys.
 * @param   {object[]} vals      - Array of values.
 * @param   {object}   [ref={}]  - Optional existing object to modify.
 *
 * @returns {object} - Object with new key-value pairs applied.
 */
function convertToObject(keys, vals, ref) {
  return keys.length === vals.length ? keys.reduce(function(obj, key, index) {
    obj[key] = vals[index];
    return obj;
  }, ref || {}) : null;
}

var keys   = ["name", "age"];
var values = ["John", 30];

document.body.innerHTML = '<pre>' + JSON.stringify(convertToObject(keys, values), null, 2) + '</pre>';

Answer №8

With the new Object.fromEntries feature, we can achieve the following:

const properties = [ "name", "age" ];
const details = [ "John Doe", "30" ];
const person = Object.fromEntries(
    details.map((detail, index) => [properties[index], detail])
);

console.log(person);

Answer №9

Here's an illustration showcasing the use of consts (non-modifying) without any external libraries.

const keys = ["Alice", "Bob", "Carla"];
const values = [30, 5, 70];
const obj = keys.reduce((acc, key, i) => {
  acc[key] = values[i];
  return acc;
}, {});
console.log(obj);

If you're open to utilizing libraries, you can explore lodash zipobject, which fulfills your specified requirements.

Answer №10

To retrieve the object containing the entries, you can arrange the arrays by transposing them.

const
    transpose = (r, a) => a.map((v, i) => [...(r[i] || []), v]),
    keys = [ "color", "size" ],
    values = [ "red", "medium" ],
    result = Object.fromEntries([keys, values].reduce(transpose, []));

console.log(result);

Answer №11

function mergeObjects(keys, values) {
    var newObject = {};
    if (keys.length !== values.length) {
        return null;
    }
    for (var i in keys) {
        newObject[keys[i]] = values[i];
    }
    return newObject;
};

var customizedObject = mergeObj(yourKeys, yourValues);

Answer №12

Here's a code snippet that can convert nested arrays into an array of key-value objects.

var keys = [
  ['#000000', '#FFFFFF'],
  ['#FFFF00', '#00FF00', '#00FFFF', '#0000FF'],
];
var values = [
  ['Black', 'White'],
  ['Yellow', 'Green', 'Cyan', 'Blue'],
];
const createObject = xs => ys => xs.reduce( (obj, x, i) => ({ ...obj, [x]: ys[i] }), {})
var newArray = keys.map((el, i) => createObject(keys[i]) (values[i]));

console.log(newArray);

The resulting output is as follows:

[
  {
    "#000000": "Black",
    "#FFFFFF": "White"
  },
  {
    "#FFFF00": "Yellow",
    "#00FF00": "Green",
    "#00FFFF": "Cyan",
    "#0000FF": "Blue"
  }
]

Answer №13

Solving the problem using a for...of loop.

let properties = ["color", "size"];
let measurements = ["red", "large"];
const output = {};
for (let [index, property] of properties.entries())
  output[property] = measurements[index];
console.log(output);
Alternatively, you have the option to utilize a toolkit like lodash that offers a function called zipObject. Example:

const properties = ["color", "size"];
const measurements = ["red", "large"];
const result = _.zipObject(properties, measurements);
console.log(result);

Answer №14

The jQuery-Plugins project features the HelperFunctions module which includes a zip functionality.

//...
zip: function(data, data2, processor) {
    var result = [];
    var processor = processor || dummyFunction;
        $.each(data, function(index, item){
        if (data2[index]) { result.push([item, data2[index]]); }
    });
    return result;
}
//...

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

Leverage the power of JSON values by incorporating them directly into HTML tags

My JSON file is generating the following styles: { "h1" : { "font-family" : "Lato", "font-size" : "24px", "line-height" : "28px", "font-weight" : 600, "colorId" : 3, "margin-bottom" : "10px", "margin-top" : "20px" }, "h2" : { ...

Execute an npm script using a gulp task

Is there a way to execute an npm script command within a gulp task? package.json "scripts": { "tsc": "tsc -w" } gulpfile.js gulp.task('compile:app', function(){ return gulp.src('src/**/*.ts') .pipe(/*execute npm run tsc*/ ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...

JSON-formatted public data sets

Can anyone point me towards a public dataset in Json format? Ideally, I am searching for one that falls within the 10-20GB range. The larger datasets I've come across so far have all been in XML format. ...

Transitioning from the Homepage to the Posts page triggered a problem due to the impact of jQuery code used on the Homepage

Recently, I integrated some jQuery code into my react code to create a fading effect on the home page components when scrolling. While it works perfectly on the homepage, I encountered an error when navigating to another page such as the 'all posts&ap ...

What is the best way to retrieve a JSON-formatted array through an AJAX call?

I am currently developing a system with two interconnected drop-down lists. The options in the second list (referred to as the 'sensor_list') are determined based on the selection made in the first list (known as the 'node_list'). To ac ...

What is the method for obtaining the _id of saved documents in Node.js and MongoDB at present?

Currently, I am working with Node.js and MongoDB and I am in need of assistance to retrieve the _id for a saved document. Here is my code: var user= new User(); user.name = 'Name'; user.email = '<a href="/cdn-cgi/l/email-protection" cla ...

Use AngularJS to extract information from Wikipedia and display it

Just starting out with angularjs and attempting to pull data from Wikipedia to display on the front end. I managed to fetch the data using the php code below: $url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&a ...

Tips for streaming JSON data with Flink

I am currently working on a data stream, receiving a series of strings and aiming to calculate the total count of all these strings. The sum is aggregated, meaning that for each subsequent record, the sum includes the previous day's total as well. The ...

Troubleshooting: Issue with running npm start | React app not loading

npm start command seems to be stuck at this particular point - https://i.sstatic.net/5NUVF.png The application is failing to load because of this issue. Here is the content of package.json file - { "name": "reacttest", "vers ...

Eliminating the use of am/pm and implementing a 24-hour format on the x-axis of a time series

Currently, I am attempting to create a time series plot with second precision in the format of HH:mm:ss (24 hours per day), as indicated in the documentation provided by moment js. However, I have encountered an issue where the format I specify is not bei ...

Ways to extract a Bearer Token from an Authorization Header using JavaScript (Angular 2/4)

When working with JavaScript, I have successfully implemented a method for authenticating to my server using an http post request. Upon receiving a response from the server, it includes a JWT in an Authorization header like this: Authorization: Bearer my ...

Tips for verifying whether a variable is a node?

Curiosity strikes me: how can I determine if the variable myVar is a node? I could simply check myVar.nodeType, but that might be misleading with something like {nodeType:1} So, naturally, I start to wonder if there's a way to do this instead: myVa ...

Tips for repairing a button using a JavaScript function in an HTML document

I am currently working on extracting titles from body text. To achieve this, I have created a button and linked my function to it. The issue I am facing is that when I click on the button, it disappears from its original position. I intend to keep it in pl ...

Determining the height of the first element in jQuery

I am dealing with multiple elements that share the same class but have different heights. The class 'xyz' is only for styling borders, as shown below: <div class='xyz'></div> //1st element height=10px <div class='xy ...

Exploring ways to incorporate mouse movements into this simple JavaScript script

I have recently decided to convert my JavaScript code into jQuery code to incorporate mouse events. After downloading the latest version of jQuery and renaming it as "jquery.js," I made modifications to my manifest.json file by adding "jquery.js." However, ...

Exploring Recursive JSON Parsing in C#

I have thoroughly reviewed all the recursive JSON sections available here, and none of them appear to be truly recursive. Nonetheless, I am faced with a challenge. How can I efficiently iterate through all the departments in this JSON file? The depth of th ...

Is it possible for JavaScript to create an object that, when accessed directly, will return a string or number, and when its property is accessed, it will return that

something like this: const object = { value: 'value', label: 'label' } object === 'value' // true, accessing it directly returns 'value' object.label === 'label' // true object.value === 'value&ap ...

Having issues with Exit Property functionality in Framer Motion when using react js

Help Needed: Framer Motion Exit Property Not Working I've been trying to get the exit motion to work on Framer Motion with React JS for over a week now, but everything else seems to be functioning correctly. I have installed the latest version of Fra ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...