What is the best way to assign the value of a specific key in one array as the key in a different array?

I am attempting to retrieve the value feature_1 associated with the key name from the array data. I then aim to set feature_1 as the key of another array asset, with an array as its corresponding value.

For example:

//input:

data: {
   name: "feature_1",
   value_a: 1,
   value_b: 2
}

//Output:

asset: {
    feature_1:[1,2]
}

Answer №1

If you're looking for a solution, consider the following code snippets:

let data = {};
if ('name' in asset) {
    let tmp = [];
    for (k in asset){
        if (k != 'name') tmp.push(asset[k]);
    }
    data[asset['name']] = tmp;
}

Alternatively, if your interpreter supports ES6, you can try this approach:

let {name, ...v} = asset;
let data = {[name]: Object.values(v)};

Answer №2

If a JSON object supports the same keys (which it doesn't seem to), you can achieve it like this:

let data= {
   name: "feature_1",
   value_a: 1,
   value_b: 2,
   value_x: 500,
   name: "feature_2",
   value_a: 17,
   value_b: 21,
   value_x: 510
}

console.log(
  Object.entries(data).reduce((a,[key,value],index)=> {
    if (key==='name')
      return {index, assets: {...a.assets, [value]:[]}};
      
    return {
      index : a.index,
      assets : {
        ...a.assets,
        [Object.entries(a.assets)[a.index][0]] : [...Object.entries(a.assets)[a.index][1],value]
      }};
  },{index:0,assets:{}}).assets
);

However, we are aware that the proper way is using separate array rows.

Answer №3

To achieve this, you can follow the steps below:

const object = {
  details: {
    title: "feature_1",
    value_x: 1,
    value_y: 2
  }
};

const result = {
  items: {
    [object.details.title]: Object.values(object.details).filter(item => item !== object.details.title)
  }
}

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

Customize the HTML tags in the Froala text editor with easy insertion and removal

In my AngularJS project, I am utilizing Froala editor. I want to create a unique functionality where a custom button wraps selected text with <close></close> tags when activated. Moreover, if the selected text is already wrapped with these tags ...

Limit the velocity of an object in Box2D using JavaScript

In my Box2D simulation, a collection of dynamic objects is experiencing various random forces. Is there a way to set a maximum speed for each object (both translational and rotational)? I considered implementing a workaround, but I'm curious if the e ...

Encountering the error message "fetch request blocked by CORS policy: No 'Access-Control-Allow-Origin' header present" on a React webpage

Even though I have experience in .NET and JavaScript, I am currently in the process of learning React. However, when trying to fetch data from my REST API, I encountered this CORS error: Access to fetch at 'https://localhost:7142/api/Campaign' ...

Animating several elements by toggling their classes

I'm struggling to implement smooth animations on this box. I've tried using 'switchClass' but can't seem to keep everything together. Any help would be greatly appreciated. Here is the code snippet for reference: <script src=" ...

Exploring the power of Angular JS promises through ng-repeat

My current project involves fetching latitude and longitude coordinates from a postcode using an API, then utilizing those coordinates to retrieve data on street level crimes near that location on a specific date through the UK police API. However, I have ...

Using useState in ReactJS does not allow setting state data

I am working with a react component that handles agreements. import React from "react"; import { AgreementInfo } from "../../../../models/shop"; import { MdClose } from "react-icons/md"; import moment from "moment"; ...

Unauthorized changes made without verification

I'm in the process of developing a website that allows users to post without needing to create an account. Upon posting, users will be prompted to enter their email address. After posting, users will receive an email with a unique URL that grants th ...

Issue with showing an input field following the button click

I'm having a bit of trouble with this function that should add an input element to a div. I've tried using appendChild and also concatenating the object to innerHTML, but no luck so far. Could it be something my beginner's mind is missing? f ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

Is it possible to populate an empty list of objects within the Page_Load scope after the page has finished loading?

I am facing a challenge where I need to populate the list var docfiles = new List<string>(); with file names uploaded by the user using dropzone js. However, the list remains empty because when the page loads for the first time, httpRequest.Files.C ...

Is it possible to apply styles to the body of a document using styled-components?

Is it possible to apply styles from styled-components to a parent element, such as the <body> tag, in a way that resembles the following: const PageWrapper = styled.div` body { font-size: 62.5%; } ` ...

Retrieving values of child elements from JSON using C#

public static void apiCall2() { WebClient c = new WebClient(); var data = c.DownloadString(baseURL + endPoint + "?access_key=" + accessKey + "&currencies=TWD&source=USD&format=1"); //Console.WriteLine(data); JObject api = JObjec ...

There seems to be an issue with the functionality of the JavaScript Quiz as it is

While working on my JS quiz, I encountered an issue where some answers were not displaying due to quotes and the need to escape HTML characters. Additionally, I am facing difficulty in accurately awarding points or deductions based on user responses. Curre ...

Show the loader animation until the browser's loading icon stops spinning

My website receives a high volume of traffic and pulls data from several servers to display on the page. It typically takes 3-4 minutes for the entire page to finish loading. Here is a preview of some of the partial page data: I am looking to add a spinni ...

Undefined Children Component

I am currently working on creating Auth routes and I am facing an issue where the children are undefined, resulting in a blank page. In my App.js file, I have implemented a PrivateRoute component as shown below. Interestingly, when I replace PrivateRoute w ...

Load a page from a different domain using uframe

Looking for a solution to successfully load an external URI using uFrame. Currently encountering an "Access Denied" issue when attempting to do so on Firefox. Any suggestions? ...

Tips for adjusting the maximum height of the column panel within the DataGrid element

I'm trying to adjust the max-height of a column panel that opens when clicking the "Columns" button in the Toolbar component used in the DataGrid. I am working with an older version of @material-ui/data-grid: "^4.0.0-alpha.8". https://i.stack.imgur.c ...

Guide to converting a compressed binary file into an array of floating point numbers

I am facing a challenge where I have to extract data from a compressed binary file and convert it into an array of floats. The only solution I have come across involves using the os module to decompress the file, then feeding it into np.fromfile for conver ...

It appears that using multiple regular expressions in LinkExtractor in Scrapy is not yielding the expected results

I have implemented my regular expressions within a JSON file which is utilized as configuration for my spider. The spider generates a LinkExtractor with rules for allow and deny regular expressions. My objective is to: crawl and extract data from product ...

Creating a Standard DIV Element (JavaScript Code)

Just a quick question here. http://jsfiddle.net/fkling/TpF24/ In this given example, I am looking to have < div>Bar 1</div> open as default... Any suggestions on achieving that? That would be all for now. Thank you so much! :D The JS script ...