Optimal approach to convert a Javascript array into an object

Below is the data structure:

 {
 bill: [ 
        { satisfy: 'true', comments: '' } 
       ],
 permission_title: [ 
        { satisfy: 'false', comments: '5' } 
       ],
 final_status: [ 
       { satisfy: 'true', comments: '' } 
       ] 
 }

I want to transform it into:

{
 bill: { satisfy: 'true', comments: '' },
 permission_title: { satisfy: 'false', comments: '5' },
 final_status: { satisfy: 'true', comments: '' } 
 }

What's the most efficient way to achieve this?

Answer №1

To simplify the object named obj, you can achieve it using the following code:

for(const prop in obj) {
    obj[prop] = obj[prop][0];
}

const obj={
 bill: [ 
        { satisfy: 'true', comments: '' } 
       ],
 permission_title: [ 
        { satisfy: 'false', comments: '5' } 
       ],
 final_status: [ 
       { satisfy: 'true', comments: '' } 
       ] 
 }
let newObj=Object.assign(obj);
for(const prop in newObj) { newObj[prop] = newObj[prop][0] };
console.log(newObj);

Answer №2

Utilize Object.entries() to extract key/value pairs. Then, employ Array.map() to iterate through the entries. Create an object for each entry with the key and value extracted from the array. Reconstruct the object by spreading it into Object.assign():

const obj = {"bill":[{"satisfy":"true","comments":""}],"permission_title":[{"satisfy":"false","comments":"5"}],"final_status":[{"satisfy":"true","comments":""}]};

const result = Object.assign(
  ...Object.entries(obj).map(([k, v]) => ({
    [k]: v[0]
  }))
);

console.log(result);

Answer №3

If each value corresponds to only one index, an alternative approach involves utilizing the reduce function in combination with the Object.keys function.

var data = {  apple: [{    ripe: 'true',    condition: ''  }],  banana: [{    ripe: 'false',    condition: '6'  }],  orange: [{    ripe: 'true',    condition: ''  }]},
    output = Object.keys(data).reduce((acc, key) => (Object.assign(acc, {[key]: data[key][0]})), {});

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

const data = {
  people: [
    { name: 'John', age: 30 },
    { name: 'Jane', age: 25 }
  ],
  places: [
    { city: 'New York', country: 'USA' },
    { city: 'Paris', country: 'France' }
  ]
};

const newData = Object.keys(data).reduce((previous, key) => {
  previous[key] = data[key][0];
  return previous;
}, {});

console.log(newData);

Answer №5

It's hard to say which method is more efficient, but the find function can also be used!

const sourceData = {
 bill: [ 
        { satisfy: 'true', comments: '' } 
       ],
 permission_title: [ 
        { satisfy: 'false', comments: '5' } 
       ],
 final_status: [ 
       { satisfy: 'true', comments: '' } 
       ] 
 };
 
 const newData = Object.keys(sourceData).reduce((previous, key) => {
    if(Array.isArray(sourceData[key])) {
        previous[key] = sourceData[key].find(() => true);
    }
    
    return previous;
 }, {});
 
 console.log(newData);

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

Removing items with properties that are null or undefined

My current situation involves using the AWS SDK, and I've noticed that many of its objects have members that can be undefined. Take for example S3.Object: export interface Object { /** * */ Key?: ObjectKey; /** * * ...

Try utilizing the 'id name ends with' parameter within the on() function for creating dynamic bindings

I need help with dynamically binding the change event to multiple select input fields that are generated within my form. The item field is generated with IDs like: id="id_form-0-item" id="id_form-1-item" id="id_form-2-item" ... Although I have attempte ...

Experimenting with Angular Jasmine to validate a factory function

As a beginner in Angular, I am diving into unit testing for the first time. Let's take a look at the module I'm working with: var app = angular. module('webportal', [ 'vr.directives.slider', 'angular-flexslider&a ...

Comparing Necessary and Deduced Generic Types in TypeScript

Can you explain the difference between these two generic types? type FnWithRequiredParam<T> = (t: T) => void type FnWithParamInferred = <T>(t: T) => void From what I understand, FnWithRequiredParam will always require the generic type t ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

Slicing a URL using JavaScript or jQuery

Hey everyone, I have a question: Can I remove the initial section of a URL? var mydir = $("script[src$='jquery_main.js']").attr('src').slice(0, -14); http://127.0.0.1:9081/Mgr/resources/ui/skins/default/js/main/ I want to get rid of ...

Save the script source in an array

When it comes to loading assets such as js & css from the next page and storing them in an Array, I have implemented a method where I iterate through the document and store the JavaScript links separately. It currently looks like this: 0:{images: Arra ...

Ways to implement the don't repeat yourself (DRY) principle in React JS with condition-based logic

https://i.stack.imgur.com/xkrEV.gif Here is a sample way to use the component: import React from "react"; import MyAvatars from "../../components/MyAvatar/MyAvatars"; const About = () => { return ( <MyAvatars ...

developing a stand-alone job listings feature

Our website features a job postings page that our clients are interested in incorporating into their own websites. This would allow applicants to easily apply for jobs directly on the client's site, with the information being saved in our system. One ...

Adding a unique key to every element within a JavaScript array

I am working with the array provided below which contains simple values. My goal is to add a key id before each value in the array, resulting in something like this: ["id:a", "id:b","id:c","id:d"]. Is there an easy way to achieve this? Any assistance would ...

Solutions for Utilizing Generic Mixins in Typescript

As a newcomer to Typescript, I have encountered an issue with mixins and generics. The problem became apparent when working on the following example: (Edit: I have incorporated Titian's answer into approach 2 and included setValue() to better showcas ...

Show occurrences of an array categorized by date using JSON format

I'm interested in analyzing a JSON array to find the occurrences of a specific item by date. Let me demonstrate with the following JSON example: "data": [ { "tags": [ "foo", "bar", "hello", "world", " ...

Issue with Angular custom tag displaying and running a function

I have created a custom HTML tag. In my next.component.ts file, I defined the following: @Component({ selector: 'nextbutton', template: ` <button (click) = "nextfunc()">Next</button> ` }) export class NextComponent{ nextfunc( ...

Enhancing speed and efficiency when zooming in on various elements using React

Issue: The zoom functionality in my React application becomes sluggish when I have over 20 components rendered. The app needs to handle zooming with thousands of components being rendered. Current zoom implementation: Currently, in my application, there ...

Leveraging JavaScript to attach/append a query parameter to a URL

Currently, I am working with the DNN CMS platform and utilizing a module called ActionForm provided by DNNSharp to generate forms. Although there is an option in this module to display a form in a popup, I am facing a challenge in passing a query string t ...

Implementing Asynchronous Rendering in React Router 4

I've been working with React Router 4 and trying to implement Redirect(Auth) following a guide. However, I'm facing an issue with rendering based on the promise returned by an AJAX call. It seems like my rendering logic inside the promise is not ...

Is it possible to access a variable outside of the immediate lexical scope in sails.js when using nested population?

I came across this answer and used it to create a solution that suited my requirements. However, for the sake of experimenting, I decided to try a different approach without using async functions and ended up diving into callback hell. Here is the version ...

Maintain loading state in parent component while the child component's react query is still loading

Within my React application, I have a parent component that sends a request to our API. While waiting for the response, a loader is displayed on the page. Once the response is received, I iterate through the data and pass each iteration to a child componen ...

Implementing asynchronous node.js output on Azure platform

Although I usually work with different programming languages, I find myself needing to incorporate some node.js code, which is entirely new to me. Currently, my goal is to have the outcome of my azure function app reliant on calling an API. To achieve this ...

Send a property parameter to the Vue component

In my project using Vue and Laravel, I am trying to create a modal window with 2 tabs. The idea is to have two buttons, with each button linked to a specific tab that should open when clicked. These buttons are located in the blade template: <button ...