[Vuejs]-How to change JSON Nested array property "project_id" with "project_name"

0👍

You can simply change your object data like any other object in JS.

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 will create 1 object that merged.

Or if you just want to project_id value then just change it like:

objCopy.project_id = obj.project_id

0👍

If I’m understanding your first question correctly, you might be interested in the map function, which allows you to create a new array from an existing array. So, for example, if the first snippet you posted is an array of objects we call projects, you could use:
var projectIds = projects.map(p => p.project_id), where projectIds would now be an array of just project ids.

It seems like you might be asking more than this though, so I second Bravo’s request for more clarification/reorganization in your question.

0👍

I’m not pretty sure if you want either of the following results:

{
"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]
}

In case you need the first scenario, the following code may help you:

// This function return an array with: [{project_id: Number}]
function onlyIds(obj) {
  const ids = [];
  // Iterate the obj Array
  obj.forEach(element => {
    // Push a new JSON: "{project_id: 1}" or whatever
    ids.push({ project_id: element.project_id });
  });
  // return an array that only contains 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);

I’m pretty sure there should be any more elegant/optimal way (as using any kind of higher-order function I may be missing right now) but as far as I understood, this should do the job.

Leave a comment