Looping through an array and adding its elements to a dictionary using JavaScript

I am struggling to figure out how to iterate over a dictionary with values in the form of arrays and then organize those values into a new dictionary. I am unsure of the steps needed to achieve this.

Below is the data I need to iterate through:

{
t: ["20181019,20181022,...."],
o: ["180.34,189.45,..."],
h: ["180.99,181.40,..."],
l: ["178.57,177.56,...."],
c: ["179.85 ,178.75,...."]
}

And here is the desired end result:

[
    { time: '20181019', open: 180.34, high: 180.99, low: 178.57, close: 179.85 },
    { time: '20181022', open: 180.82, high: 181.40, low: 177.56, close: 178.75 },
    { time: '20190509', open: 193.31, high: 195.08, low: 191.59, close: 194.58 },
]

Answer №1

If you want to get the desired outcome, you can make use of the Object.keys function along with reduce

const obj = {
  a: ["apple, apricot"],
  b: ["banana, blackberry"],
  c: ["cherry, coconut"],
  d: ["date, dragonfruit"],
  e: ["elderberry, fig"],
};

const dictionary = { a: "fruitA", b: "fruitB", c: "fruitC", d: "fruitD", e: "fruitE" };

const tempObj = Object.keys(obj).forEach((key) => (obj[key] = obj[key][0].split(",")));

const finalResult = Array.from({ length: obj.a.length }, (_, index) => {
  return Object.entries(obj).reduce((accumulator, [key, value]) => {
        accumulator[dictionary[key]] = key === "a" ? value[index] : +value[index];
    return accumulator;
  }, {});
});

console.log(finalResult);
/* This section is not related to the solution. It is just for adjusting output height. Please disregard it */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Below is a simple solution:

const data = {
  t: ['20181019,20181022,....'],
  o: ['180.34,189.45,...'],
  h: ['180.99,181.40,...'],
  l: ['178.57,177.56,....'],
  c: ['179.85 ,178.75,....'],
};

let transformed = {};
Object.keys(data).map((key) => {
  transformed[key] = data[key][0].split(',');
});

const result = transformed.t.map((tVal, index) => {
  return {
    time: tVal,
    open: transformed.o[index],
    high: transformed.h[index],
    low: transformed.l[index],
    close: transformed.c[index],
  };
});

console.log(result);

Answer №3

Here is the code snippet to achieve the desired result.

let stockData = {
  t: ["20181019,20181022"],
  o: ["180.34,189.45"],
  h: ["180.99,181.40"],
  l: ["178.57,177.56"],
  c: ["179.85 ,178.75"]
}

let result = [];

const openPrices = stockData.o.toString().split(",");
const highPrices = stockData.h.toString().split(",");
const lowPrices = stockData.l.toString().split(",");
const closePrices = stockData.c.toString().split(",");

stockData.t.toString().split(",").forEach((item, index) => {
  result.push({
    time: item,
    open: openPrices[index],
    high: highPrices[index],
    low: lowPrices[index],
    close: closePrices[index]
  });
})

console.log(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

Emphasize the most recent file during the document upload process and ensure the scroll bar moves accordingly to the document

I am currently working on a feature where the scroll bar should move to the newly uploaded document in a list of documents. When I upload a new document, I want the scroll bar to automatically move to that document. Currently, the highlighting changes to t ...

The correct usage of && and || operators in javascript

I've developed a small web application and I'm facing an issue where I want to trigger an alert when the 'enter' key is pressed if there is an empty or space value. Currently, the alert appears not only on hitting 'enter' but ...

The average duration for each API request is consistently recorded at 21 seconds

It's taking 21 seconds per request for snippet.json and images, causing my widget to load in 42 seconds consistently. That just doesn't seem right. Check out this code snippet below: <script type="text/javascript"> function fetchJSONFil ...

The JSON object is not providing the length of the array, returning the value as

I'm currently fetching JSON data from a PHP file in the following manner: $.getJSON('fresh_posts.php',function(data){ global_save_json = data.freshcomments; var countPosts = data.freshposts; var howManyPosts = countPosts.length; ...

Tips for removing residue from old watches

Our angularJS web components are integrated with a jqxGrid. Whenever a user makes edits in a cell, we implement a custom typeahead editor using Angular. However, I have noticed that after the editor is destroyed, my $watches array does not revert back to i ...

Keep the Bootstrap modal open while the JavaScript validation is running, and redirect the form action if the validation is successful

When trying to execute the submit event from a form, my code is supposed to keep the modal open if validation fails. However, for some reason, this functionality is not working as expected. var myForm = document.updteform; var condition = true; if ...

Manipulating divs by positioning them at the top, left, right, bottom, and center to occupy the entire visible portion of the page

Many suggest avoiding the use of table layouts and opting for divs and CSS instead, which I am happy to embrace. Please forgive me for asking a basic question. I am looking to create a layout where the center content stretches out to cover the entire visi ...

What causes the mounted hook in Vue to be triggered multiple times when used within a plugin or mixin?

How can I prevent repetitive behavior in my code? Is this a bug that needs fixing? Take a look at the plugin below: const globala = { install(Vue) { Vue.mixin({ mounted() { console.log('hi') } }) } } And here&apos ...

Issue occurred while executing the fs.rename() function in a loop in Node.js

I'm currently working on a project that involves organizing uploaded files into folders based on their request ID. I am using express-request-id to retrieve this ID. The issue I am facing is that whenever there are multiple files to be moved, the pro ...

difficulty encountered when using the Angular delete method in conjunction with Express.js

I am trying to send a delete request to my Express server from Angular. remove: function (id) { return $http({ method: 'DELETE', url: '/users/delete/'+ id }) } In my Expr ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

Issue encountered in Angularjs during upgrade process from version 1.2.27 to 1.4.7

Recently, I upgraded my app from using AngularJS 1.2.27 to version 1.4.7, but now I am encountering an error in the AngularJS file. SyntaxError: Unexpected token : (angular.js:12477) at Function (native) at Object.sd. ...

Can Google Charts columns be customized with different colors?

Is it possible to modify the colors of both columns in Google's material column chart? Here is the code I am using for options: var options = { chart: { title: 'Event Posting', subtitle: 'Kairos event p ...

Toggle visibility on the child DOM element of each item in the v-for loop

Here's an example of a template: <template> <table class="table table-hover"> <tbody> <tr> <th style="width:260px">Info</th> <th>Deta ...

The Chrome extension I created using JQuery to trigger 'keyup' events is not updating the value of the 'input' field on a website that utilizes knockout JS

I am currently working on developing a Google Chrome extension for a website that appears to be utilizing 'knockout JS'. Let's take a look at the HTML element below: <input type="text" class="form-control text-right" id="amount" autoco ...

Viewing Server Logs in a Discord Channel

My gaming server stores logs in .txt format, and I'm looking for a way to automatically send updates to a Discord channel whenever there is new log data. I am currently developing a Discord bot using Node.js. Does anyone have any suggestions on how I ...

I am continuously encountering an error message saying [$injector:modulerr] while working with AngularJS

I've been reviewing my JavaScript code thoroughly, but I can't seem to pinpoint any major issues. The error message I'm encountering is as follows: Uncaught Error: [$injector:modulerr] Failed to instantiate module careApp due to: Error: [$i ...

Include an additional tag solely by using a specific set of keys predetermined in advance

After getting inspiration from Stackoverflow, I decided to enhance my text-box with a tagging feature. The first step was downloading and adding the http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js file to my ASP.NET web folder, allowing me to u ...

Just starting out with jQuery: seeking advice on a user-friendly slideshow plugin, any tips on troubleshooting?

I am currently trying to incorporate a basic jquery slideshow plugin, but I seem to be encountering some difficulties. The documentation mentions the need to install 'grunt' and 'node dependencies', which is confusing to me as I am new ...

How to determine if an Angular list has finished rendering

I am facing an issue where I have a large array that is being loaded into a ul list using ng-repeat in Angular. The loading of the list takes too long and I want to display a loader while it's loading, but hide it only when the ul list is fully render ...