Combining data from an object within an array in JavaScript

I am looking for a way to incorporate values from an Object (weekdayMap) into an existing array (vehicleAvailabilities) that contains objects. I require the value Montag on day one and Dienstag on day two.

This pattern continues for each day of the week.

The desired result should be:

const result = [
  {id: 1, day: "1", value: true, weekday: 'Montag'},
  {id: 2, day: "2", value: true, weekday: 'Dienstag'} ...

based on these arrays:

const vehicleAvailabilities = [
  {id: 1, day: "1", value: true},
  {id: 2, day: "2", value: true},
  {id: 3, day: "3", value: true},
  {id: 4, day: "4", value: true},
  {id: 5, day: "5", value: true},
  {id: 6, day: "6", value: false},
  {id: 7, day: "7", value: false}
]

const weekdayMap = {
  1: 'Montag',
  2: 'Dienstag',
  3: 'Mittwoch',
  4: 'Donnerstag',
  5: 'Freitag',
  6: 'Samstag',
  7: 'Sonntag'
}

Answer №1

Using ES6 syntax.

const data = [{id:1,day:"Monday",value:true},{id:2,day:"Tuesday",value:true},{id:3,day:"Wednesday",value:true},{id:4,day:"Thursday",value:true},{id:5,day:"Friday",value:true},{id:6,day:"Saturday",value:false},{id:7,day:"Sunday",value:false}];
const weekdays = {1:'Montag',2:'Dienstag',3:'Mittwoch',4:'Donnerstag',5:'Freitag',6:'Samstag',7:'Sonntag'};

const result = Object.keys(weekdays).map((key, index) => ({ weekday: weekdays[key], ...data[index] }));

console.log(result);

Answer №2

Check out this demonstration, where I showcase my love for using array map and exploring new functional coding techniques in JavaScript.

const vehicleAvailabilities = [
  {id: 1, day: "1", value: true},
  {id: 2, day: "2", value: true},
  {id: 3, day: "3", value: true},
  {id: 4, day: "4", value: true},
  {id: 5, day: "5", value: true},
  {id: 6, day: "6", value: false},
  {id: 7, day: "7", value: false}
]

const weekdayMap = {
  1: 'Monday',
  2: 'Tuesday',
  3: 'Wednesday',
  4: 'Thursday',
  5: 'Friday',
  6: 'Saturday',
  7: 'Sunday'
}
let re = vehicleAvailabilities.map(function(item){
    item.weekday = weekdayMap[item.day];
  return item;
})
console.log(re);

Answer №3

Create your custom function to achieve this:

const carAvailability = [
  {id: 1, day: "Monday", status: true},
  {id: 2, day: "Tuesday", status: true},
  {id: 3, day: "Wednesday", status: true},
  {id: 4, day: "Thursday", status: true},
  {id: 5, day: "Friday", status: true},
  {id: 6, day: "Saturday", status: false},
  {id: 7, day: "Sunday", status: false}
]

const weekDayMapping = {
  1: 'Monday',
  2: 'Tuesday',
  3: 'Wednesday',
  4: 'Thursday',
  5: 'Friday',
  6: 'Saturday',
  7: 'Sunday'
}

function combineMapWithArray(mapping, arr) {
  return arr.map((item) => { item.dayOfWeek = mapping[item.id]; return item; });
}

console.log(combineMapWithArray(weekDayMapping, carAvailability));

Answer №4

Check out this example script that utilizes the map function to easily add a new property to objects.

var carAvailability = [
  {id: 1, day: "1", available: true},
  {id: 2, day: "2", available: true},
  {id: 3, day: "3", available: true},
  {id: 4, day: "4", available: true},
  {id: 5, day: "5", available: true},
  {id: 6, day: "6", available: false},
  {id: 7, day: "7", available: false}
];
const dayOfWeekMap = {
  1: 'Monday',
  2: 'Tuesday',
  3: 'Wednesday',
  4: 'Thursday',
  5: 'Friday',
  6: 'Saturday',
  7: 'Sunday'
}
var output = [];
var obj;
for(var j=0;j<carAvailability.length;j++){
obj = carAvailability[j];
obj.weekday = dayOfWeekMap[parseInt(obj.day)];
output.push(obj);
}
console.log(output);

Answer №5

For those using typescript or ES6, @Álvaro Touzón's suggestion can be simplified even further:

const updatedAvailability = vehicleAvailabilities.map(item => item.weekday = weekdayMap[item.day])

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

What is the best way to extract and transform the Json data received from a stream builder into widgets within a flutter app?

I am a beginner in flutter and I have a question about working with Stream builders. I am getting a JSON response with maps nested in lists and I need help accessing these fields to display widgets on the screen. Can someone please assist me with this? He ...

Is there a way to convert JSON to a Java object through mapping?

ObjectMapper mapper=new ObjectMapper(); String response1=client.execute(request1, responseHandler); Map jsonObject=mapper.readValue(response1, Map.class); List<Integer> idsList = new ArrayList<>(); JSONArray jsonArray = jsonObject.getJSON ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Delaying the search in Jquery until the input is finalized

Is there a way to delay the search trigger until the user finishes typing? I'm utilizing a function created with mark.js () which initiates the search as the user types, resulting in jumping to the first result during the search. However, the issue is ...

Positioning the label for a Material-UI text field with an icon adornment when the shrink property is set

https://i.stack.imgur.com/E85yj.png Utilizing Material-UI's TextField, I have an Icon embedded within. The issue arises when the label "Your good name here" overlaps the icon instead of being placed beside it. This problem emerged after I included ...

Navigate to link based on selected option in Bootstrap select menu

How can I make a page redirection based on the selected option value from a bootstrap select? Here is the HTML code: <select class="selectpicker"> <option value="https://example.com/">Home</option> <option value="https://exam ...

Unable to send a namespaced action from a different module: [vuex] action type is not recognized

In my coding project, I am working with two different modules called activities and alerts. One of the requirements is that whenever an activity is added, I need to trigger an alert action with the namespaced identifier alerts/SHOW. This functionality was ...

Is there a way to set up automatic switching to a minimized browser window when receiving an alert, even if you are currently using a different window like Outlook or Explorer?

Is there a way to automatically switch to a minimized browser window from a different program window (such as Outlook or Explorer) when an alert is received on a specific tab? I'm looking for a Javascript/Jquery solution. I've attempted the foll ...

Component fails to update when state updated using useState()

In my current project, I am facing an issue with a parent (App) and child (MUIDatatable) component setup. The child component is a datatable that requires a columns prop to define the structure of the columns, including a custom render function for one of ...

Are you encountering issues with retrieving $http results from the cache?

During my initial $http requests, I am saving the results in cache using two functions in my controller. Both functions call the same function in a service which handles the $http request. The first function successfully saves the results in cache, but whe ...

Guide on making a JavaScript button with both "light and dark" modes

Currently, I am attempting to change the color scheme of the page by adjusting the :root variables using a function called changeBackgrondColor(). This function is then assigned to the fontAwesome moon "button". However, when I click on the moon, the pag ...

Encountering a WriteableDraft error in Redux when using Type Definitions in TypeScript

I'm facing a type Error that's confusing me This is the state type: export type Foo = { animals: { dogs?: Dogs[], cats?: Cats[], fishs?: Fishs[] }, animalQueue: (Dogs | Cats | Fishs)[] } Now, in a reducer I&a ...

What is the importance of having the http module installed for our Node.js application to function properly?

After exploring numerous sources, I stumbled upon this code snippet in the first application: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); r ...

JQuery plugin for creating interactive date selection forms

Having some trouble creating a dynamic form. The datepicker seems to only work on the first row and I can't click it. Tried a few different codes but no luck so far. Below is the code excluding the PHP part, which is just for inserting into a database ...

Can we utilize the elements in Array<keyof T> as keys in T?

Hello, I am trying to develop a function that accepts two parameters: an array of objects "T[]" and an array of fields of type T. However, I am encountering an issue when I reach the line where I invoke el[col] Argument of type 'T[keyof T]' i ...

Associating checkbox options with an array that is void of elements

I have a series of arrays linked to checkboxes and I am trying to create a unique array based on the selected checkbox values. Here is an example of the HTML structure: <input type="checkbox" value="value1">Value 1 <input type="checkbox" value=" ...

Obtain array buffer from NodeJS to capture frames from a video file

My current goal is to extract frames from a video in node without relying on a video tag. I am utilizing openvg-canvas for this task, which allows me to print images and use the canvas API functionalities successfully. The challenge lies in the fact that ...

Javascript tells the time difference between 1 minute and 1 minutes. A timer is set up to notify when the time is

self.calculateMessageTime = function calculateMessageTime(receiveDate){ var dateReceived = Date.parse(receiveDate); var now = new Date(); now = Date.now(); // in seconds var difference = Math.abs(dateReceived - now)/1000; if(differ ...

Having trouble saving user input from a form to a database using axios, mongodb, and vue?

I am a beginner in working with Vue and I'm currently facing an issue while trying to submit user input data to my MongoDB using axios. Although the data from the database is displayed on the page, I can't seem to get the form input data to succe ...

What is the method for passing the Rating field value in Vue.js?

Here is the structure of my form: <form id="enquiryBox" method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);"> <div class="modal-body brbottom-20"> <div class="clearfix"> < ...