Manipulate objects in Vue.js by converting them into an Array of Objects, each containing a key and its

Is there a way to convert this object into an array of objects?

const failed = { 
  "4579043642": "Lodge with set number '4579043642' exists!",
  "4579043641": "Lodge with set number '4579043641' exists!",
  "4579043640": "Lodge with set number '4579043640' exists!",
}

The desired output should be like this:

[
  {
    "fieldName": "4579043642",
    "message": "set number '4579043642' exists!"
  },
  {
    "fieldName": "4579043641",
    "message": "set number '4579043641' exists!"
  },
  {
    "fieldName": "4579043640",
    "message": "set number '4579043640' exists!"
  }
]
data() {
  return {
    formattedList: [],
  };
},

I have attempted conversion using the following method;

uploadFeedbackReject: {
  handler: function(newFeed) {
    if (failed) {
        this.formattedList = [response.failed];
      }
  },
  immediate: true,
  deep: true,
},

Your assistance would be greatly appreciated.

Thank you.

Answer №1

This code snippet is functioning perfectly

const errors = {
  123456789: "Item with ID '123456789' already exists!",
  987654321: "Item with ID '987654321' already exists!",
  2468101214: "Item with ID '2468101214' already exists!",
};

const errorArray = Object.entries(errors).map((item) => ({
  fieldID: item[0],
  errorMessage: item[1],
}));

console.log(errorArray);

Answer №2

Iterate over the object properties and create an array of objects with each property as a field name and its value as the message:

const formerList = {
  "4579043642": "Lodge with set number '4579043642' exists!",
  "4579043641": "Lodge with set number '4579043641' exists!",
  "4579043640": "Lodge with set number '4579043640' exists!",
}

let resultArray = []

for (prop in formerList) {
  resultArray.push({
    fieldName: prop,
    message: formerList[prop]
  })

}

console.log(resultArray)

Alternatively, you can map over the object properties to achieve the same result:

const formerList = {
  "4579043642": "Lodge with set number '4579043642' exists!",
  "4579043641": "Lodge with set number '4579043641' exists!",
  "4579043640": "Lodge with set number '4579043640' exists!",
}

let resultArray = []

resultArray = Object.keys(formerList).map((field) => {

  return {
    fieldName: field,
    message: formerList[field]
  }
})

console.log(resultArray)

Answer №3

To iterate through the object, you can utilize Object.keys() to extract both the name and value pairs, then store them in a new object before adding it to an array.

let obj = {
  daisy: "qwerty",
  eve: 7,
  frank: 54.32
}

let arr = [];

for(let j=0; j<Object.keys(obj).length; j++){

  // Extracting the name and value from the original object
  let key = Object.keys(obj)[j];
  let val = obj[key];
  
  // Creating a new object with the extracted data
  let newObj = {
    label: key,
    content: val
  }

  // Adding the new object to the array
  arr.push(newObj);
}

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

Tips for integrating Grails ${createLink} into your javascript code

Below is a JavaScript function that I have: function GetSelectedItem() { var e = document.getElementById("country"); var strSel = e.options[e.selectedIndex].value; alert(strSel); var url = "${createLink(controller:'country', act ...

What strategies can be used to scale up a website's images in proportion to their page views or traffic?

The situation: On my simple HTML website, I have a group of images placed side by side. Each image is connected to a specific article, and when you hover over the image, a detailed description of the linked article pops up in the center of the page. The o ...

Send the array of data to the table in a separate component

I am currently working on developing a basic online shop using React. For testing purposes, I have not integrated it with any API or database yet. Instead, I am utilizing an array of data to display items on the homepage. My goal is to enable visitors to a ...

Ajax updates to an element are not reflected until the for loop has completed

I am looking for a way to print a series of numbers sequentially using AJAX. Here is an example of what I want to achieve: (each new line represents an update of the previous line!) Output is: 1 12 123 1234 12345 123456 ... I ...

How to dynamically display content based on option selection in AngularJS using ng-show

I am trying to create a functionality where my input field is bound to my select option. When the select option is set to Yes, I want the input field to be visible, and when it's set to No, I want the input field to be hidden. (function(){ var app ...

Updating the list state does not trigger a re-render in Next.js/React

Currently, I have the following state setup: const [places, setPlaces] = useState(false) const [selectedPlaces, setSelectedPlaces] = useState([]) I am asynchronously fetching data to populate the places state by calling an API. The returned array of objec ...

The error message "CommonFunctions is not defined" appears due to an uncaught ReferenceError

I have a pair of external javascript files, one named CommonFunctionsJS and the other known as DealerCreateOrderJS. The DealerCreateOrderJS is specifically called within a view. However, I encounter an error whenever attempting to invoke a function from ...

Tips for handling a disabled button feature in Python Selenium automation

When trying to click this button: <button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button> I need to remove the disable attribute to make the button clickable. This ...

Tips for showing information in a column based on a selection in a webgrid handsontable

Is there a way to organize data into columns based on a select option? I've looked at the documentation, but it's quite complex. Can anyone offer some guidance? var settings={ data: [] , minSpareRows: 20, columns: [ {type: 'dropdown&apo ...

What is the best way to ensure consistency in a value across various browsers using Javascript?

I am currently developing a feature on a webpage that displays the last update date of the page. The functionality I am aiming for is to select a date in the first input box, click the update button, and have the second box populate the Last Updated field ...

What are the steps to confirm form submission with $pristine and $dirty in Angular?

I recently created a form using the resources available at https://github.com/nimbly/angular-formly and . While most of the validation is being handled by Angular, the user-friendliness of the form validation needs improvement. I am looking to implement va ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

Execute functions upon the completion of jQuery ajax requests

I need to trigger my function loadTest() once the bootstrap dialog is fully loaded and displayed. $(".btn").on("click", function() { $.ajax({ type: "POST", url: '/echo/html/', data: { html: '', ...

Determining if a user's email is already in use with the account-password package

One of the challenges I'm facing in my app involves checking for registered users. Specifically, when a user is typing their email address to log in, I want to verify if they exist with each keystroke and provide feedback accordingly. Here is the cod ...

Maintain the property characteristics (writable, configurable) following the execution of JSON.parse()

Imagine a scenario where an object is created elsewhere and passed to my module. It could have been generated on the server in node.js, or perhaps in a different module where it was then serialized using JSON.stringify() for transmission (especially if it ...

Display alternative component upon button click in React.js

After creating the default layout, I'm aiming for a scenario where clicking each button only alters specific parts of the layout through the content component. React router is being utilized to manage different pages. Each button corresponds to a uni ...

JavaScript modularizing for early termination

When considering a method to exit a function early based on a certain condition, the following code example can be helpful: function abc() { if (some_condition) { message('blah'); return; // exit the function early } // carry out o ...

How to Align a Button in the Middle with Bootstrap?

Hey there! I'm working on creating a video list. I've utilized the bootstrap grid system to put it together. Here's the code I have so far: I'm trying to center the play button both vertically and horizontally within the thumbnail. Any ...

What is the best way to retrieve search data using Express and MongoDB?

I have successfully implemented my CRUD Code, and now I am looking to add a search functionality with dynamic values. const express = require('express') const router = express.Router() const cors = require('cors') //Importing Jobs Mode ...

Having problems uploading and resizing images using Express.js

var express = require("express"), app = express(), formidable = require('formidable'), util = require('util'), fs = require('fs-extra'), qt = require('quickthumb'); // Utilizing quickthumb ap ...