Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue:

[
{
"project_id": 1,
"project_name": "CDP",
"role": "PL"
},
{
"project_id": 2,
"project_name": "Admincer",
"role": "PM"
},

I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific method.

My approach is: 1. Initially, I want to transfer the "project_id" values from this array to a second nested JSON array.

Research conducted:

const obj = {
"project_id": 1,
"project_name": "CDP",
"role": "PL"
};;
const objCopy = {
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": 1, 1,
"work_day_id": 45,
"time_cards": [
{
... obj
}
]
};;
console.log (objCopy);

The copying process was successful when tested in Chrome Console; however, the entire object got copied instead of just the "project_id" property.

I aim to introduce a new property named "prj_name" in this array and exhibit only that property within Vuetify.

async fetchWorkerTimeCard() {
  try {
    this.worker_data = [] 
    await this.$axios.$get('/worker_time_card', {
      params: {
        work_date: this.calendarVal
      }
    }).then(data => {
      this.worker_data = data
    })
    var projects = await this.fetch_worker_projects()
    console.log(projects)
  } catch (error) {
    console.log(error)
    this.worker_data = []
  }
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.5/vue.js"></script>
<v-card>
  <v-data-table v-if="worker_data.time_cards" :headers="headers2" :items="worker_data.time_cards"></v-data-table>
</v-card>

Answer №1

Modifying object data in JavaScript is a simple task, similar to changing any other object.

const obj = {
  "project_id": 1,
  "project_name": "CDP",
  "role": "PL"
};

const objCopy = {
  "start_time": "09:00:00",
  "end_time": "18:00:00",
  "rest_time": "01:00:00",
  "worked_time": "08:00:00",
  "is_wfh": true,
  "id": 1,
  "work_day_id": 45
}

console.log({...obj, ...objCopy})

This code snippet will result in the creation of a merged object.

If you only need the value of project_id from 'obj', you can simply assign it like this:

objCopy.project_id = obj.project_id

Answer №2

If I am interpreting your initial inquiry correctly, you may find the map function useful. This function allows you to generate a new array based on an existing one. For example, if the snippet you provided represents an array of objects named projects, you can utilize:

var projectIds = projects.map(p => p.project_id)
, which will create an array containing only the project ids.

However, it appears that there is more to your query. Therefore, I support Bravo's suggestion for additional clarification or restructuring in your question text.

Answer №3

It's uncertain which of the two results you're looking for:

{
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": [
    1,
    1
],
"work_day_id": 45,
"time_cards": [
    {
        "project_id": 1
    },
    {
        "project_id": 2
    }
]

}

or this

    {
    "start_time": "09:00:00",
    "end_time": "18:00:00",
    "rest_time": "01:00:00",
    "worked_time": "08:00:00",
    "is_wfh": true,
    "id": [
        1,
        1
    ],
    "work_day_id": 45,
    "time_cards": [
"project_id": [1, 2]
}

If the first scenario is what you need, the provided code snippet could assist you:

// This function returns an array with: [{project_id: Number}]
function onlyIds(obj) {
  const ids = [];
  // Iterate through the obj Array
  obj.forEach(element => {
    // Push a new JSON: "{project_id: 1}" or similar
    ids.push({ project_id: element.project_id });
  });
  // return an array containing only the project_id
  return ids;
}

const obj = [
  {
    project_id: 1,
    project_name: 'CDP',
    role: 'PL',
  },
  {
    project_id: 2,
    project_name: 'Admincer',
    role: 'PM',
  },
];
const objCopy = {
  start_time: '09:00:00',
  end_time: '18:00:00',
  rest_time: '01:00:00',
  worked_time: '08:00:00',
  is_wfh: true,
  id: [1, 1],
  work_day_id: 45,
  time_cards: onlyIds(obj),
};
console.log(onlyIds(obj));
console.log(objCopy);

There might be more elegant or optimal solutions available (like using higher-order functions), but based on my current understanding, this approach should get the job done.

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

How to encase HTML content within a scope variable without relying on ng-bind-html

Is there a way to include HTML content using a scope variable in AngularJS without utilizing ng-bind-html-unsafe? <div ng-controller="dataController">{{test}}</div> $scope.test = "<div>Html content</div>" ...

What steps do I need to follow to write this function in TypeScript?

I am encountering a problem when building the project where it shows errors in 2 functions. Can someone please assist me? The first error message is as follows: Argument of type 'IFilmCard[] | undefined' is not assignable to parameter of type &a ...

When utilizing auth0, an error occurs during the grunt build process

I successfully developed a small project using AngularJS on my local machine without encountering any issues. However, when I attempted to build the project with Grunt, everything stopped working and an error occurred: vendor.ce3c01a3.js:2 Error: [$inject ...

"Efficiently sharing information in a multi-tenant application: strategies for seamless data transfer between front

In my development of a multi tenancy application using Node.js/Mongoose and React, I made the decision to utilize a single database for all users. The main collection, dubbed companies, serves as storage for basic company data and includes a unique compan ...

Error in calculation of $.post function in JQuery

I am facing an issue with my file delete.php, which contains the following code: <?php $folder = "./fak/"; $filename = $_POST['name']; unlink($folder.$filename); ?> Additionally, I have an index.html file with the below code: <html ...

How to incorporate a JSON schema as an array in PHP

In my PHP code, I am attempting to insert a new key and its corresponding content into a JSON file. $content = file_get_contents($_POST["content"]); $decode = json_decode($content,true); $version = $_POST["version"]; array_unshift($decode['versions&a ...

Is it possible to activate the identical drop-down or popover with multiple buttons?

Is it possible to activate the same drop-down menu with multiple buttons? For example, I want a button at the top of the page labeled special menu, another in the middle also labeled special menu, and one at the bottom as well labeled special menu. When a ...

The absence of 'www' in the ajax path is causing an error

Apologies for my poor English as I am currently a student. My issue is related to the use of ajax without "www" in the URL. Let me demonstrate. var path = "www.sinemayolu.com"; //Real-time Ajax Search $('.searchtext').keyup(function ...

Tips for converting JSON information on a website and inserting it into a designated division?

I've recently delved into front-end development, searching for solutions and hints without much success. I'm currently in the process of building my first website, specifically a "find recipes" website. Lacking knowledge of API calls, I created a ...

I was caught off guard by the unusual way an event was used when I passed another parameter alongside it

One interesting thing I have is an event onClick that is defined in one place: <Button onClick={onClickAddTopics(e,dataid)} variant="fab" mini color="primary" aria-label="Add" className={classes.button}> <AddIcon /> & ...

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

Acquire key for object generated post push operation (using Angular with Firebase)

I'm running into some difficulties grasping the ins and outs of utilizing Firebase. I crafted a function to upload some data into my firebase database. My main concern is obtaining the Key that is generated after I successfully push the data into the ...

Style HTML in VSCode just like you do in Visual Studio

Trying to figure out how to configure VSCode to format HTML (and other markup files like .vue) in a similar way to Visual Studio. In Visual Studio, if I write something like: <div id="testid" class="test" style="display: block;"> <p class="p ...

Displaying images with Javascript when they are clicked

How can I make a speech bubble appear when the image of the person is clicked? <div> <p style="float: left;"><img src="person.png" border="1px"></p> </div> <script> function bubblespeech() { document.getEl ...

Having Trouble with Shopify's Asynchronous Ajax Add to Cart Feature?

I have developed a unique Shopify page design that allows users to add multiple items to their cart using Shopify's Ajax API. I've created a test version of the page for demonstration: Below is the current javascript code I am using to enable as ...

Leveraging partial string of JSON key value for conditional statements

I have obtained some JSON data with a structure similar to the following: { "events": [ { "event": { "event_instances": [ { "event_instance": { "id": 1365348, "ranking": 0, ...

Code in Javascript that performs a check for pre-order traversal

I’m interested in writing a preorder traversal code in Java for JavaScript. I’ve been practicing this question on geeksforgeeks: Check if a given array can represent Preorder Traversal of Binary Search Tree This is the algorithm they provided: 1) Cr ...

Extract the year from a string formatted as 1880-01-01T00:00:00.000

Looking to extract the year from an array of dates with format 1880-01-01T00:00:00.000. What's the most efficient method to accomplish this using JavaScript? ...

The second tab on Bootstrap5's tab content feature seems to generate an endless amount of white

I am working on a project where I need to display statistics for both the current month and year. To organize this data, I created a card with tabs for each - one tab for the month and another for the year. By default, the month tab is loaded first. Howev ...

What is the proper placement for index.html <head/> class helper functions within a ReactJS Component?

My custom helper functions are stored in a JavaScript file called classie.js: ( function( window ) { 'use strict'; function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } var hasClass, ...