Reputation: 2075
I am having to different arrays. For eg :
Array 1 is :
[536, 549]
Array 2 is :
[
{ text: "ABCD", value: 341 },
{ text: "WXYZ", value: 439 }
]
I want to create an object as:
[
{
fieldId: 536,
value: {
value: 341,
display_value: "ABCD"
}
},
{
fieldId: 549,
value: {
value: 439,
display_value: "WXYZ"
}
}
]
I have no idea how to do this. Thanks in advance. :)
Upvotes: 1
Views: 50
Reputation: 4763
const arr_1 = [536, 549]
const arr_2 = [{text: "ABCD", value: 341},{text: "WXYZ", value: 439}]
// with map
let new_arr = arr_2.map( (ele, index) => {
return {
fieldID: arr_1[index],
value: { value: ele.value, display_value: ele.text }
};
});
// with for loop
let new_arr2 = [];
for(let i = 0; i < arr_2.length; i++){
new_arr2.append({
fieldID: arr_1[i],
value: { value: arr_1[i].value, display_value: arr_1[i].text }
});
}
Documentation for map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Documentation for arrays: https://developer.mozilla.org/en-US/docs/Glossary/array
Documentation for objects: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object
Not sure if it is desired to have the numbers as string. You would have to use toString()
. Also not sure if it should be a json string in the end, to get that use JSON.stringify()
Upvotes: 3
Reputation: 1562
const arr1 = [ 536, 549 ];
const arr2 = [
{ text: "ABCD", value: 341 },
{ text: "WXYZ", value: 439 }
];
const result = arr1.map((value, index) => ({
fieldId: value,
value: {
display_value: arr2[index].text,
value: arr2[index].value
}
}));
Here, result
will hold the desired value.
Upvotes: 0