Loop through an array in JavaScript to create properties for an object

When working with Vue, I encountered a prop that is actually an array containing multiple types of items. For each item in this array, I want to create a property in a specific object. For example, if the array includes methods and count, I aim to construct an object like this:

   const data = {
       name: newObject.name,
       methods: newObject.methods,
       count: newObject.count,
       // Any other properties will be added here
   }; 

Here is the JavaScript code I currently have:

this.inputs.forEach((input) => {
   // Property creation logic will go here
});

            // Should I create properties here?
            // What about newObject.methods ?

    // Define a data object for a post request
   const data = {
       name: newObject.name,
       // Any other properties will be added here
   };

How can I achieve this? I considered using a forEach loop, but I'm unsure about what to do next.

The prop looks like this:

`:inputs="['Methods']"`

My idea is to loop through this inputs prop and create a property in the newObject object for each item in the array.

Answer №1

It seems like you're attempting to extract a property within a component and then iterate through that property to store it locally using a forEach loop,

Check out this demonstration in the following Fiddle: https://jsfiddle.net/eywraw8t/70166/

Vue.component('child', {
  props: ['data'],
  data: function() {
    return {
        'newItems': [],
    }
  },
  mounted: function(){
    this.data.forEach((input) => {
        this.newItems.push(input.data)
    });


    console.log(this.newItems)
  },
  template: `<div>{{ newItems }}</div>`
});

new Vue({
  el: "#app",
  data() {
    return {
      data: [
          { 'data': 123, 'other': 678 },
          { 'data': 233, 'other': 6728 },
          { 'data': 343, 'other': 67812 },
        ]
    }
  }
});

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 building a carousel-style transition using React Router

I am looking to implement a carousel animation in my React Router. My website has pages named A, B, C, and D. When transitioning from page A to B, I want the animation to move from right to left. When going from B to A, I want it to move from left to rig ...

What is the best method for extracting the innerHTML value of html tags using a css selector or xpath?

I am currently struggling with retrieving the HTML inner text value using CSS selector or XPath. While I can achieve this using document.getElementById, I am unable to do so using selectors. I can only print the tag element but not the text from it. For e ...

SecretKey is not valid, FirebaseError code: 400

Currently, my backend is powered by Firebase. However, when I initiate it using NODE_ENV=debug firebase emulators:start --inspect-functions, the following messages are displayed: emulators: Starting emulators: auth, functions, storage ⚠ functions: Ru ...

Arrange the JSONB data type with sequelize literal in your order

My current approach involves querying for all items using the following structure: const filteredItems = await allItems.findAll({ where: conditions, include: associations, order: sortingCriteria, limit: limit, o ...

Tips for accessing nested JSON values using Selenium

Here is a JSON snippet to work with: "ACCOUNT": { "AmountDue": "$36,812.99", "OutstandingBalance": "$27,142.27", "StatementTotal": "$9,670.72", "StatementDate": "12/6/2018", "DueByDate": "12/23/2018", ...

extracting an attribute from a class's search functionality

Let's consider the following HTML structure: <div id="container"> <div> <div class="main" data-id="thisID"> </div> </div> </div> If I want to retrieve the value inside the data-id attribute ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...

Issue encountered while retrieving values from JSON for the data table

I recently developed an application using a combination of React and Flask to display JSON data in a table format. While I can successfully see the data loaded in the console, I encountered difficulties in rendering it within the data table. The technologi ...

Error: The function subscribe in _store_js__WEBPACK_IMPORTED_MODULE_12__.default is not supported

In my main App component, I am subscribing to the store in a normal manner: class App extends Component { constructor(props) { super(props) this.state = {} this.unsubscribe = store.subscribe(() => { console.log(store.getState()); ...

Error: The specified function (0, _ignore.getFileExtensions) is not a valid function

Using Vue CLI version 3.5.5 After installing vue-cli and creating a new project with the create command, an error occurred at the end of the process. What steps should be taken to resolve this issue? ? Please select a preset: Manually choose features ? ...

Stopping React component click event from bubbling up to document

How do I prevent a click event in a React component from bubbling up to the document? There seems to be an issue that needs fixing! Let's see if we can resolve it on our own. I have a box component with a click event listener, and some link compone ...

What could be causing my .vue component to be undefined?

I've encountered an issue while using parcel-plugin-vue to compile a basic .vue component from a file. The compilation process seems to be running smoothly with no errors, but when I try to view the page in my browser, it appears blank without any con ...

Sorting functionality malfunctioning after dynamically adding new content using AJAX

Greetings to all, I have a question about my views. 1- Index 2- Edit In the index view, I have a button and AJAX functionality. When I click the button, it passes an ID to the controller which returns a view that I then append to a div. The Edit view con ...

I consistently encounter the error message 'XRWebGLLayer is not defined no-undef' while implementing three.js within react.js to develop a WebXR application

Trying to implement WebXR with Three.js in a React project, encountering the error: 'XRWebGLLayer' is not defined no-undef for baseLayer: new XRWebGLLayer(session, gl) The code works fine in vanilla JavaScript but fails to compile in React. ...

Checking for Age Validity with Formik and Yup: How to Ensure a Date Represents Someone Who is Eighteen Years Old or Older

I'm currently working on a form using Formik, Yup, and ReactJS. Specifically, I am focusing on the date field validation to ensure that the user is at least 18 years old. Within the validationSchema parameter in Formik, I have included the following c ...

Tips for running a function at regular intervals in NodeJS

I've experimented with the setInterval() method before. While it seemed ideal, the problem I encountered was that it didn't start the first call immediately; instead, it waited for X seconds before producing the desired value. Is there an alterna ...

JavaScript plugin designed for effortless conversion of JSON data to structured HTML code

I want to add this JSON data to an HTML element. [ { "website":"google", "link":"http://google.com" }, { "website":"facebook", "link":"http://fb.com" } ] Is there an easy way to convert this using a plugin ...

In this JavaScript code, learn how to organize an array based on its numerical property

What is the best way to organize an array based on the 'num' property in this JavaScript array? var data = [{ 005: { `num`: 1360487}, 047: { `num`: 2519472}, 061: { `num`: 1559115}, 081: { `num`: 2232710}, 085: { `num`: 54956 ...

Is it possible to eliminate the dedupe feature in npm?

By mistake, I accidentally ran the command npm dedupe and now all of my node_modules directories are flattened. While this reduces file size, it's making it more difficult to find things. Is there a way to reverse this and return to the hierarchical f ...

Achieving a similar functionality to Spring Security ACL in a Node.js AWS Lambda serverless environment

I am tackling a javascript challenge that has me stumped. Specifically, I am trying to figure out how to implement fine-grained authorization using an AWS serverless approach. In Spring security ACL, users can be banned from specific tasks at the instanc ...