Creating a JSON object from two arrays is a simple process

Consider the following two arrays:

let values = ["52", "71", "3", "45", "20", "12", "634", "21"];
let names = ["apple", "orange", "strawberry", "banana", "coconut", "pineapple", "watermelon", "plum"];

Is there a way to combine them into an object like this:

{
    "apple": 52,
    "orange": 71,
    "strawberry": 3,
    "banana": 45,
    "coconut": 20,
    "pineapple": 12,
    "watermelon": 634,
    "plum": 21
}

I experimented with Object.assign but it only changed the values.

Object.assign<any, any>(names, values);

I also attempted using Object.defineProperties, but I couldn't get it to work, or maybe I just don't understand how to properly use it.

UPDATE

I gave this approach a try:

    let temp = {};

    names.forEach((item, index) => {
        console.log('item: ', item);
        console.log('index: ', index);
        console.log('temp[item]: ', temp[item]);
        console.log('values[index]: ', values[index]);
        temp[item] = values[index];
        console.log(names);
    });

But unfortunately, it didn't produce the desired result.

https://i.sstatic.net/HEgfx.png

Answer №1

Create a brand new result-object, and for each name in the names array, add a new object to this object containing the name and corresponding value.

Revised: Since all elements in the values array appear to be strings while the values in the result-object are integers, I have used parseInt for conversion purposes.

Important: It is not recommended to use a variable named name as it may cause a TypeError when attempting to perform actions like name.forEach or name.map. This issue appears to stem from it being a reserved word or having special significance.

let values = ["52", "71", "3", "45", "20", "12", "634", "21"];
let names = ["apple", "orange", "strawberry", "banana", "coconut", "pineapple", "watermelon", "plum"];

let temp = {};
names.forEach((elem, index) => { temp[elem]=parseInt(values[index]) });

names.forEach((item, index) => {
  console.log('item: ', item);
  console.log('index: ', index);
  console.log('temp[item]: ', temp[item]);
  console.log('values[index]: ', values[index]);
  temp[item] = values[index];
  console.log(names);
});

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

"Enhance Your Website with Custom jQuery Preloaders

Currently, I am facing a challenge while developing a website. Specifically, I am struggling with resolving the issue of a blank page being displayed. The website that I am working on involves functionality where swiping right triggers data insertion into ...

Access the outcome by utilizing a for loop

Within my code, I am utilizing both a function and a loop: var songs = Musics.searchSongs(query).then(function(rs) { return rs; }); for (var i = 0; i < songs.length; i++) { console.log(songs[i]); } I am now looking for a way to execute the ...

How can I retrieve information from a topic using kafka-node?

Having trouble reading data from a Kafka server? You may encounter an error message stating that the topic does not exist. Here are some questions to guide you: 1- How can I ensure that my Kafka connection is established? 2- What is the process for retri ...

In a production environment, disable caching for server functions in Next.js

In my Next.js 14 project, I have a page that utilizes default Server-side Rendering (SSR) to fetch data and pass it to client components. export default async function Page() { const magazines = await getMagazines(true); return ( <Box sx= ...

The error message "count(): Parameter should be in the form of an array or an object that implements the Countable interface, determined by the size

The error is being triggered in the code snippet below only when the array returned is too lengthy. It seems to work fine with short arrays, although it's unclear how short is "short". $phone_numbers = array(); if(!empty($_POST['phone_numbers&ap ...

What are the memory-saving benefits of using the .clone() method in Three.js?

As I work on my game project, I am including a whopping 100,000 trees, each represented as a merged geometry. Utilizing the tree.clone() method to add them from a cloned model has helped save a significant amount of memory. Unfortunately, the game's p ...

How can I properly consume the variables 'b0' and 'b1' from the JSON response in my Java POJO class?

How can I access the 'b' variable data from a JSON response containing 'b0' and 'b1' variables in my Java POJO? Here is an example of the JSON response: { "@a":"abc", "b0":{ "@name":"b0", "@nodes":[]}, "b1":{ ...

Creating a Gulp automation task to handle ng-constant across various environments

I've been attempting to make this work, but it seems like I might be overlooking something. I'm utilizing ng-constant and configuring different environment endpoints as outlined in the ng-constants issue However, my setup involves using gulp and ...

Tips on incorporating asynchronous functionality in AngularJS

I am currently utilizing AngularJS version 1.5.8 and have a specific requirement. When the user clicks on the Next button, the text inside the button should change to 'Processing...' before completing the operation. I have implemented the $q serv ...

jQuery conceal input field after it has been displayed

I've created an HTML form with two different sections for search purposes. The first section displays basic fields, and by clicking on "Advanced Search" (in my case, "Расширенный поиск"), additional fields are revealed. Everything work ...

What is the correct way to execute the query "select * from table where indexA >= 'a' order by indexB ASC limit 10" in indexedDB?

As I delve into learning about javascript IndexedDB, I have encountered a challenge in executing complex queries. My goal is to perform a select query like this one: "select * from table where indexA >= 'a' order by indexB ASC limit 10" I a ...

Javascript Pretty Print Format is producing inaccurate output

function displayData(info) { document.body.appendChild(document.createElement('pre')).innerHTML = info; } function searchInGitHub(str) { const http = new XMLHttpRequest(); http.open("GET", "https://api.github.com/search/reposi ...

What could be causing my JSON request to fail so frequently, with a success rate of less than 50%

In the process of developing a spelling bee game that retrieves words from the Oxford Dictionary API, I am encountering a higher failure rate than desired. The success rate hovers around 25 to 36 percent, with many words resulting in nil responses, which I ...

Issue with RxDB: Collection not found upon reload

Exploring the integration of RxDB in my Angular project. I wanted to start with a simple example: export const LANG = { version: 0, title: "Language Key", type: "object", properties: { key: { type: "string", primary: true } }, requ ...

Utilizing the Spread Operator in combination with a function call within the props of the Tab component in Material UI

I came across this code snippet in Material UI: <Tab label="Item One" {...a11yProps(1)} />. It uses the spread operator (...) with a function call within the props. However, when I tried to use it separately like: console.log(...a11yProps(3 ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

What is the best way to bring in a file or subfolder from a folder that has been

Currently, I am facing a situation where I need to specify to TSC in the tsconfig file that I want to include specific files or subfolders from a folder while ignoring others. How can I achieve this? For instance: /. |-folder 1 |->file2.ts |-& ...

Differences Between 'this' and 'self' in Classes

I am currently working with ES6 Classes and I'm struggling to grasp why I am able to access the this variable within one of the methods. //CODE class Form{ constructor(){ var self = this; } assemble(){ log(self); ...

Using Jquery to input selected dropdown values into a text input field

Currently, I am facing some challenges in achieving this task. My goal is to have the selected option from a dropdown list called programs_dropdown added to a text field named programs_input, with the option values separated by commas. For example: php, j ...

The user values in jQuery alert function are correct, but the saveorupdate function fails to save null values in the database table

While using the alert function in jQuery, the user input values are alerted correctly, but for some reason they are being stored as null in the database table. Can anyone help me identify what might be causing this issue or what I might be doing wrong? I& ...