How to map an object of arrays with Javascript - javascript

I need to map an object of arrays. Once mapped I want to display the first row of content in a div. I have an object of arrays coming from the db and I'm only mapping 2 of the 4 arrays within the object.
What I want to be able to do is use the mapped arrays and then get all the data that corresponds with that mapped array and display it all in a div. The user can click an up or down arrow and then change what is displayed, but I'm having trouble getting it to show the next or prev data in the object. I have the clicking function properly set up (worked with test data) just think it's not working because I'm not mapping it correctly.
Original object coming from db:
object: {
PageNum: [array of items],
RowNum: [array of items],
CustomerName: [array of items],
FacilityName: [array of items]
}
mapping the arrays:
var delDS = [{
pageNum : delPageData["PageNum"],
rowNum : delPageData["RowNum"]
}];
var delMappedArray = delDS.map(function(obj) {
var rObj = {};
rObj[obj.pageNum] = obj.rowNum;
return rObj;
});
which returns something like this:
[object]
0: Object
2,2,4,4,6: Array(5)
0: "24"
1: "26"
2: "2"
3: "4"
4: "10"
length: 5

Try something like this:
//map the data
delPD = delPageData.PageNum.map((x,i) => ({
pageNum: x,
rowNum: delPageData["RowNum"][i],
cName: delPageData["CustomerName"][i],
fName: delPageData["FacilityName"][i],
}));
//sort the data
delPD.sort(function(a,b) {
if(a.pageNum == b.pageNum) {
return (a.rowNum - b.rowNum);
} else {
return (a.pageNum - b.pageNum);
}
});
//give the data an index number for ordering purposes later
for(var i=0; i<delPD.length; i++) {
delPD[i].index = i;
}
This is first mapping the array of objects and creating a new array. Then you are sorting the new array by page numbers and putting them in order. Then you're adding an index number to each object. This way you can use it later in your code if need be.
Hope this helps!

Related

Within a nested array, can I create an array of the keys at each index?

Goal: For each key, assign every value to an array.
Use case: I have to be able to search using all possible values simultaneously. As seen at the bottom, a possible key:value search would be:
"LocationNumber": [1,2,3,4]}
The problem: Object SettingOptions is a nested array.
This is how I log each key within a given index:
//Defines array 'keysArray'
const keysArray = [];
pm.test("array of SettingsOptions[0] keys", () => {
arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions[0]; //object 'SettingOptions[0]' calls 1st settingoption
//For each property in array, add the property to 'keysArray'
for (var property in arrayOfObject) {
keysArray.push(property)
}
console.log(keysArray)
});
Response:
(11) ["LocationNumber", …]
0: "LocationNumber"
1: "StoneCount"
2. ....
....
9: "Shape"
10: ...
To create an array of values from a given property:
pm.test("array of SettingsOptions objects", () => {
arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions;
let arrayLocationNumber = arrayOfObject.map(a => a.LocationNumber);
// console.log(Object.values(arrayLocationNumber));
});
Response:
[1, 2, 3, 4]
What I'm looking for:
There is a lot of variation in the data I'm pulling from. So I need to be able to automagically pull values to be able to reference them in subsequent requests. An acceptable response could look something like:
0.{"LocationNumber": [1,2,3,4]}
1....
2.......
3.{"Shape": ["Center","Halo","Accent 1","Accent 2"]}

Update Ugly Object Keys Using Another Array

Below array is called Data, it's array of objects with keys like "marketValue"
Below array is called Columns, it's array of objects with each has Header (Pretty name for columns) and id (Ugly name for columns)
How to scroll through Data and update all ugly keys like this "marketValue" to "Market Value" using columns array?
This is how far I got, but it doesn't work, it returns undefined for every singe row:
let PrettyData = Data.map((row) =>
Object.entries(row).forEach(
(key) => {
let newKey = columns.filter((colRow) => colRow.id === key[0]);
let obj = {newKey: key[1]}
return obj;
}
)
);
If I understand correctly, you want to update the the keys of each object in data with the Header value of that columns object. This should do it:
const prettyMapping = {};
columns.forEach((column)=>{
prettyMapping[column.id] = column.Header
});
const PrettyData = Data.map((row)=>{
const prettyRow = {};
Object.keys(row).forEach((column)=>{
prettyRow[prettyMapping[column]] = row[column]
});
return prettyRow
});
Go through the columns and create a mapping of header to id.
Map over the rows. Map will create a new array with whatever is returned from each original row iteration
In each row iteration, create the newly formatted row using our mapping from before.
For this case:
const Data = [{qty:1, mp:2}, {qty:1, mp:2, mv:2}];
const columns = [{id:"qty",Header:'Quantity'}, {id:"mv",Header:'Market Value'}, {id:"mp",Header:'Market Price'}]
The above code returns:
[ { Quantity: 1, 'Market Price': 2 },
{ Quantity: 1, 'Market Price': 2, 'Market Value': 2 } ]
Hope this helps!

How can i add a new object property to existing object in javascript?

I have an array of objects, let's say array[object,object....] . I want to add a new property to each object inside an array.
Below i have mentioned and existing array and the resulted one which i want.
Existing array :
array[ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf",}
{"name":"Brijesh mishra","add":"jkfhgfbrfhiurf"} ]
I want this array :
array[ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf","mobile":"95937338373"}
{"name":"Brijesh mishra","add":"jkfhgfbrfhiurf","mobile":"78984983498"} ]
How can i do this ?
You can do like this. Let there be an array of mobile number whose length is same as the length of array. Loop through the array array and add the mobile key and value from mobNum array
var mobNum=[1,2];
var array = [{
"name": "Siddhesh mishra",
"add": "hjhjjdjkhjibf"
}, {
"name": "Brijesh mishra",
"add": "jkfhgfbrfhiurf"
}]
array.forEach(function(item,index){
item.mobile=mobNum[index]
})
console.log(array)
var data = [ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf"},
{"name":"Brijesh mishra","add":"jkfhgfbrfhiurf"} ];
data.map(function(entry){
//add logic to get mobile number from entry.name or entry.add
return entry.mobile = '98989898';
})
console.log(data);

Can I create an object without a name in JS?

I have a structure that looks like this:
var set_2 = {
nameofSet : 'French greetings',
category: 'languages',
cards : [
{
front : 'bonjour',
back : 'dzien dobry'
},
{
front : 'bonne nuit',
back : 'dobranoc'
},
{
front : 'bon soir',
back : 'dobry wieczor'
}
]
}
I can iterate over them in a loop like this:
var cards = set_2.cards;
for (k = 0;k<cards.length;k++) {
var frontSide = cards[k].front;
var backSide = cards[k].back;
}
Do I assume correctly that in the cards array I have a couple of objects without names?
If so, how can I push more objects like that to the cards array without giving them names? I want to create those objects in a for loop.
I'm not sure what you mean by names, but you can push more objects into the array as such:
set_2.cards.push({front: 'front', back: 'back'});
Q: Do I assume correctly that in the cards array I have a couple of
objects without names?
A: Yes, they do not have property names like object properties do, but they each have an index, like arrays have, as in 0, 1, 2.
Or rather:
set_2.cards[0]
set_2.cards[1]
set_2.cards[2]
Q: If so, how can I push more objects like that to the cards array
without giving them names?
A: As the accepted answer says:
set_2.cards.push({front: 'front', back: 'back'});
These new objects that you push into the array will not have names, but they will have indices(or "indexes").
In summation, an element of an array is indicated by its index number(JavaScript Number), while an entry in an object is indicated by its property name(JavaScript String).
You can't create an object without names in it. Either object with names or just a normal array but you can create object with name followed by arrays inside.
Object -> object_name -> Array -> object -> object_name -> Array
var set_2 = {
nameofSet : 'French greetings',
category: 'languages',
cards : [
{
front: ['bonjour', 'bonne nuit', 'bon soir'],
back: ['dzien dobry', 'dobranoc' 'dobry wieczor']
}
]
}
'bonjour'
console.log(set_2.cards[0].front[0]);
'dobranoc'
console.log(set_2.cards[0].back[1]);
push into front
set_2.cards[0].front.push('Hello');
push into back
set_2.cards[0].back.push('Hello');
You can use the push() method like this
var set_2 = {
nameofSet : 'French greetings',
category: 'languages',
cards : [
{
front : 'bonjour',
back : 'dzien dobry'
},
{
front : 'bonne nuit',
back : 'dobranoc'
},
{
front : 'bon soir',
back : 'dobry wieczor'
}
]
}
var cards = set_2.cards;
var obj = { front:"front1", back:"back1"};
cards.push(obj);
for (k = 0;k<cards.length;k++) {
var frontSide = cards[k].front;
var backSide = cards[k].back;
console.log(backSide);
}
Regarding the question about having a few objects without names. If I understand it correctly, you have one main object. Its name is "set_2". The rest such as "nameofSet", "category", and "cards" are the names of properties of the object.
"cards" has an array value that appears to have empty objects with the "front" and "back"properties, if you are asking this*.

Remove a record in a Object Array jQuery

EDIT : Included more details
Hi I have a Object Array in jQuery which looks like this,
My question is how can I delete a record from that object array by columnheader as parameter. I know there is this
var result = $.grep(records, function(e){ return e.columnheader == currentheader; });
but grep i only used to check if there's a matching data based on currentheader that i passed in. What if I want to delete?
I want to delete a record on the fly as I am looping in that object array, lets I have. data contains all object arrays that is shown in the image.
$.each(data, function(key,value) {
// Let's say I want the code here to delete a record in the current object array that I'm looping into.
});
Thanks
You can use filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
arr = arr.filter(function(e) {
return e.columnheader !== currentheader;
});
Demo
var arr = [{
name: 'John Skeet',
rank: 1
}, {
name: 'T.J.Crowder',
rank: 10
}];
console.log(arr);
arr = arr.filter(function(e) {
return e.rank !== 10
});
console.log(arr);
UPDATE
I want the code here to delete a record in the current object array that I'm looping into
Changing a property from object in array.
var arr = [{
name: 'John Skeet',
rank: 1
}, {
name: 'T.J.Crowder',
rank: 10
}];
$.each(arr, function(index, obj) {
if (obj.rank === 10) {
arr[index].rank = 9;
}
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
You can use the JavaScript splice method to do it. First find the index of your object in the array then use the method like that :
your_array.splice(obj_index,0);
EDIT
The easy way but not optimized is to use a for loop to get the index, a better solution is to use linq.js to get the object, then your_array.indexOf(your_obj);
EDIT 2
You can download linq.js here Linq.js
You can use it like this:
function DelteObjFromArray(your_value){
var objToDelete = Enumerable.From(your_array).Where(function (x) { return x.your_property == your_value; }).FirstOrDefault();
var objIndex = your_array.indexOf(objToDelete);
your_array.splice(objIndex,1);
}

Categories

Resources