I am interested in retrieving an array

Here is the array I am working with

{ Colors: 'Blues',
  Department: 'Clearance',
  Size: [ 'Runners', 'Custom Sizes' ],
  Shape: 'Round',
  Designer: 'B. Smit',
 }

The desired output should be :

{ Colors: 'Blues',
  Department: 'Clearance',
  Size: 'Runners',
  Shape: 'Round',
  Designer: 'B. Smit',
 }
{ Colors: 'Blues',
  Department: 'Clearance',
  Size: 'Custom Sizes',
  Shape: 'Round',
  Designer: 'B. Smit',
 }

I have attempted the solution above but it is not giving me the expected result

Answer №1

You could potentially implement a solution along these lines

function transformInput(input){
  var updatedArray = [];
  for(var index = 0; index< input.Size.length; index++){
    updatedArray.push({
      Colors: input.Colors,
      Department: input.Department,
      Size: input.Size[index],
      Shape: input.Shape,
      Designer: input.Designer
    });
  }
  return updatedArray;
}


transformInput({
  Colors: 'Blues',
  Department: 'Clearance',
  Size: [ 'Runners', 'Custom Sizes' ],
  Shape: 'Round',
  Designer: 'B. Smit',
});

Answer №2

If you are utilizing ES6 or a modern web browser...

const details = {
    Type: 'Shirts',
    Color: 'Red',
    Size: [ 'Small', 'Medium', 'Large' ],
    Brand: 'Nike',
    Design: 'Logo'
};

const updatedDetails = details.Size.map(size => (
    Object.assign(
        {},
        details,
        {
            Size: size
        }
    )
));

alert(JSON.stringify(updatedDetails, null, '\t'));

Answer №3

@sunnyn, give this solution a try. It should provide you with the assistance you need.

 var data = { Type: 'Fruit',
             Color: 'Red',
             Shape: 'Round',
             Quantity: 10,
             Origin: 'USA',
};

var newDataArr = [];

for(var key in data.Quantity) {
    var newObject = {};
     for (var prop in data){
          if (data.hasOwnProperty(prop)) {
             newObject[prop] = data[prop];
          }
     }
     newObject.Quantity = data.Quantity[key];
     newDataArr.push(newObject);
}

console.log(newDataArr);

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

Creating a unique texture on a spherical object using THREE.js

Can a sphere be textured in sections rather than all at once? Just like we can use 6 textures on 6 sides of a cube, is it possible to apply different textures to different parts of a sphere? For example, dividing the sphere into quarters and texturing each ...

Video playback disabled on hover in Chrome browser

I have added videos to a search results page. When the user hovers over the video, I want to show a preview of it in a separate container and start playing the video. $(".videoSearchResults video").mouseenter(function () { var container = document.cre ...

Embed the parent component within the child component

I have two files called Recursive.vue and Value.vue. Initially, when Recursive is the parent component, mounting Recursive within itself works perfectly. Similarly, mounting Value within Recursive and then Value within itself also works fine. However, an ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Implementing JavaScript functionality upon page load with ASP.NET

I have come across a situation where I am trying to integrate working code (jQuery/Javascript) that makes an API call and sends data to it. The API service then responds with a success or failure message based on the data insertion into the API db. Everyth ...

Creating a Full Height Background Image with a Responsive Width Using Jquery

I am facing an issue with my background image dimensions of 1400 in height and 1000 in width. When using any full-screen background jQuery plugin or code, the image crops from either the top or bottom to fit the entire screen. However, I am looking for a s ...

Transform an array of strings into a JSON object or array

Is there a way to transform a JavaScript string array into a JSON string? var arr = "{'id': '10', 'name': 'test1'},{'id': '11', 'name': 'test2'}"; This would allow for easy a ...

Dynamically insert <td> elements into <tr> element using both jQuery and JavaScript

I am facing an issue with adding a new table data (td) element dynamically to the first table row (tr) in my JavaScript code. Here is the original table before adding the new td element: <table> <tbody> <tr> <t ...

Smooth carousel navigating through dots

I am currently using the slick carousel from http://kenwheeler.github.io/slick, and I am looking for a way to limit the number of dots to 8 even when there are more than 8 slides. The navigation dots should include arrows on the left and right sides to in ...

Guide on incorporating CSS into a JavaScript function

Currently, I am utilizing a jQuery monthly calendar where each day is represented by a cell. When I click on a cell, I can trigger an alert message. However, I also want to modify the background color of the specific cell that was clicked. Unfortunately, ...

Continuously update the content within a paragraph using jQuery

After searching for a jQuery animation that would constantly change text within a paragraph, I stumbled upon a solution at this link : Text changing with animation jquery. However, I encountered a challenge as I wanted to include a bootstrap button beneath ...

Develop a personalized conditional rendering directive in Vue.js

I am exploring how to create a custom Vue conditional directive. While I could simply use a global method and call it within a v-if, I prefer the idea of having a dedicated directive for clarity in my code. My objective is to apply this directive to an el ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...

Organize chat messages based on date using JavaScript

I came across a similar query, but it didn't resolve my issue. Check this out: How can I group items in an array based on date? My goal is to organize these chat messages by date after fetching them from the database using AJAX. The console displays ...

What is the best way to add data to a URL in an ActionResult Method using window.location.href?

I am having trouble understanding how to retrieve data using window.location.href = '/Product/Success/'+data.OrderTrackNo+'';. I am able to get data using ajax, but it seems different when retrieving data with window.location.href, whic ...

Ways to trigger a function when the body is loaded

In this snippet, I am attempting to execute the oauth2_login() function when the body loads, which is intended to log in the user. Currently, I have hardcoded values from the database into the username and password fields. <!DOCTYPE html> <html&g ...

Utilizing Javascript / jQuery to eliminate specific CSS styles

I am facing an issue with the CSS code for a table positioned at the bottom of the screen. The current code includes a filter specifically for IE 8, but I need to make it compatible with IE 10 as well by removing the filter and adding a background color. ...

Troubleshooting permission problems with Yarn and node_modules in a Docker environment

I have a Docker container containing a Symfony 6 web application and various other services like php-fpm, node, and python. Additionally, I have separate containers for MySQL and Nginx, all running on Alpine 3.15. My current issue arises when I execute do ...