I have used Lodash to get to this structure where i needed to group by id .
The grouping by works fine but i want to add more properties to the head of the group by field like its name and domain, from the nested object , how do i do that.
Extra - Also In future if i need to Filter the contents inside the nested object like using status or by the publisher name how do i add that . Very new to Javascript
let result = _.chain(value)
.groupBy('pubId')
.pairs()
.map(function(currentItem) {
return _.object(_.zip(['publisherId', 'targetting'], currentItem));
})
.value();
The data returned by this
{
"publisherId": "17",
// add name , domain , here
"targetting": [
{
"id": 1,
"pubId": 17, // remove this
"type": 18,
"value": "google.com,yahoo.com",
"status": 12,
"createTs": null, // remove this
"updateTs": null,// remove this
"createUser": null,// remove this
"updateUser": null,// remove this
"percentage": 0,// remove this
"rtbSspPublishers": { // remove this
"id": 17,
"name": "Tom's Hardware",
"domain": "www.tomshardware.com",
"extPublisherId": 17
}
},
{
"id": 2,
"pubId": 17,
"type": 14,
"value": "Sports,Fashion",
"status": 12,
"createTs": null,
"updateTs": null,
"createUser": null,
"updateUser": null,
"percentage": 0,
"rtbSspPublishers": {
"id": 17,
"name": "Tom's Hardware",
"domain": "www.tomshardware.com",
"extPublisherId": 17
}
},
{
"id": 3,
"pubId": 17,
"type": 11,
"value": "Sports,Fashion",
"status": 12,
"createTs": null,
"updateTs": null,
"createUser": null,
"updateUser": null,
"percentage": 0,
"rtbSspPublishers": {
"id": 17,
"name": "Tom's Hardware",
"domain": "www.tomshardware.com",
"extPublisherId": 17
}
}
]
}
I need to remove certain properties from the nested grouping how do i acheive that using lodash i am using lodash 3.0.0 .Please help thanks
Just iterate the result again and delete those properties which are not required.
For example
var propsToBeDeleted = [ "createTs", "updateTs" ]; //array of properties to be deleted
result = result.map( function(item){
propsToBeDeleted.forEach( function(prop){
delete item[prop];
});
return item;
});
Or try updating your lodash code as
let result = _.chain(value)
.groupBy('pubId')
.pairs()
.map(function(currentItem) {
var item = _.object(_.zip(['publisherId', 'targetting'], currentItem));
propsToBeDeleted.forEach( function(prop){
delete item[prop];
});
return item;
})
.value();
Related
I have an array originalArrayData like so:
Expanding:
The value of the first array item, which is an object, is several objects. An example of the contents of the first part of the array is as such:
originalArrayData = [{
"16": {
"id": 22,
"grid_row_id": 5,
"grid_col_id": 16,
"data": "10",
"created_at": "rertte",
"error_mgs": null
},
"header": "Row 2",
"id": 5
},
{
"17": {
"id": 31,
"grid_row_id": 9,
"grid_col_id": 17,
"data": "14",
"created_at": "rtyhtyjtdyj",
"error_mgs": null
},
"header": "Row 1",
"id": 6
},
{
"18": {
"id": 35,
"grid_row_id": 9,
"grid_col_id": 12,
"data": "55",
"created_at": "thrtuhrs",
"error_mgs": null
},
"header": "Row 1",
"id": 6
}...........
Let's say I have an array of ids (these numbers could be random and there isn't always 2. There could be 1, 3, etc. array items)
arrayOfIds: [16 , 17]
If the value of grid_col_id is present anywhere in the arrayOfIds, how can I retrive the 'data' value from each object and put it in its own array?
I know how to retrieve an array of all ids from each first object within the array:
let data = this.arrayList.map((obj) => obj.id);
The above yields: [5,6,7,8,9]. However, it's now correct for what I am attempting. So far I have the following:
var targetArr = []
this.originalArrayData.forEach(item=> {
item.forEach(ins => {
if(arrayOfIds.includes(ins.grid_col_id)
targetArr.push(ins.data)
})
})
which yields an error: TypeError: row.forEach is not a function
My TARGET is: [10, 14, ...]
The target contains 10 and 14 because if you look at the originalArrayData, if grid_col_id is inside arrayOfIds: [16 , 17], then we retrieve the "data" value and put it inside a new array.
How can I achieve the target array?
You can do as follows. See comments in the code for explanation
let od = [{
"16": {
"id": 22,
"grid_row_id": 5,
"grid_col_id": 16,
"data": "10",
"created_at": "rertte",
"error_mgs": null
},
"header": "Row 2",
"id": 5
},
{
"17": {
"id": 31,
"grid_row_id": 9,
"grid_col_id": 17,
"data": "14",
"created_at": "rtyhtyjtdyj",
"error_mgs": null
},
"header": "Row 1",
"id": 6
},
{
"18": {
"id": 35,
"grid_row_id": 9,
"grid_col_id": 12,
"data": "55",
"created_at": "thrtuhrs",
"error_mgs": null
},
"header": "Row 1",
"id": 6
}]
let filter = [16, 17];
//transform the original data into a flat array of objects
let dd = od.map(x =>
//all property values of the object
Object.values(x)
//which are an object (ie filter away primitve types
.filter(y => typeof y === "object"))
//flatten the array of arrays
.flat()
let result = dd
//filter the list of objects for the ids in the filter
.filter(x => filter.includes(x.grid_col_id))
//and get only the data property
.map(x => x.data)
console.log(result);
Here you go:
const input=[{"16":{id:22,grid_row_id:5,grid_col_id:16,data:"10",created_at:"rertte",error_mgs:null},header:"Row 2",id:5},{"17":{id:31,grid_row_id:9,grid_col_id:17,data:"14",created_at:"rtyhtyjtdyj",error_mgs:null},header:"Row 1",id:6},{"18":{id:35,grid_row_id:9,grid_col_id:12,data:"55",created_at:"thrtuhrs",error_mgs:null},header:"Row 1",id:6}];
const arrayOfIds = [16 , 17];
const format = (array) => {
return array.reduce((result, el) => {
const key = Object.keys(el).find((key) => 'object' === typeof el[key]);
if(arrayOfIds.includes(+key)){
result.push(+el[key].data);
}
return result;
}, []);
};
console.log(format(input));
Here's an alternative that more closely resembles your original attempt.
You can use Object.keys, Object.hasOwn and Array.prototype.find to get the key of the property with grid_col_id:
const originalArrayData = [{
"16": {
"id": 22,
"grid_row_id": 5,
"grid_col_id": 16,
"data": "10",
},
"header": "Row 2",
"id": 5
},
{
"17": {
"id": 31,
"grid_row_id": 9,
"grid_col_id": 17,
"data": "14",
},
"header": "Row 1",
"id": 6
},
{
"18": {
"id": 35,
"grid_row_id": 9,
"grid_col_id": 12,
"data": "55",
},
"header": "Row 1",
"id": 6
}]
const arrayOfIds = [16, 17]
const targetArr = []
originalArrayData.forEach(d => {
const keyOfObjectWithGridCol =
// Get all keys of the object as an array
Object.keys(d)
// Get the key of the nested object that has grid_col_id
.find(key => Object.hasOwn(d[key], 'grid_col_id')) // Find property
if (arrayOfIds.includes(d[keyOfObjectWithGridCol].grid_col_id)) {
targetArr.push(d[keyOfObjectWithGridCol].data)
}
})
console.log(targetArr) // [10, 14]
I have an array of objects like this one:
let arr1 = [{
"ref": 1,
"index": "300",
"data": {
"id": 10,
"status": {
"code": "red"
}
}
}, {
"ref": 2,
"index": "301",
"data": {
"id": 20,
"status": {
"code": "blue"
}
}
}];
I want to replace the status.code by the one given in this other array of objects:
let arr2 = [{
"id": 10,
"content": {
"name": "green"
}
}, {
"id": 20,
"content": {
"name": "yellow"
}
}];
My idea is to map the first array and the use the find function (or filter) to loop the second array and when the ID's match change the values but I'm missing something, how can i do this the most optimized for performance and readability way?
let res: any[];
res = arr2.map((x: any) =>
arr1.find((y: any) =>
(y.data.id === x.id) ? 'logic if match' : 'return'
));
I would first change the format of arr2 in such a way that it is easier to access in such a format: (If you can easily change how you get this data, it would be better I think. Otherwise, transform the data as below.)
const idStatusCodeMap = {
"10": "green",
"20": "yellow"
}
We do this so we can just look if there is idStatusCodeMap[10] or idStatusCodeMap[anyId]. This makes it possible that you only loop through arr1, not a nested loop for both arr1 and arr2.
Then, loop through arr1 and replace the colours if necessary. If suppose, a new colour is not found on idStatusCodeMap, such as for id = 30, then don't do anything for that.
let arr1 = [{
"ref": 1,
"index": "300",
"data": {
"id": 10,
"status": {
"code": "red"
}
}
}, {
"ref": 2,
"index": "301",
"data": {
"id": 20,
"status": {
"code": "blue"
}
}
}];
let arr2 = [{
"id": 10,
"content": {
"name": "green"
}
}, {
"id": 20,
"content": {
"name": "yellow"
}
}];
let idStatusCodeMap = {}
//transpiling arr2 to more performant hashMap
arr2.forEach(item => {
idStatusCodeMap[item.id] = item.content.name;
})
console.log(idStatusCodeMap);
arr1 = arr1.map(item => {
//if the id of an item in arr1 is found in code map, replace it with new value.
//if not found, it will skip.
if(idStatusCodeMap[item.data.id]) {
item.data.status.code = idStatusCodeMap[item.data.id]
}
return item;
})
console.log(arr1);
For each object inside this array containing userHandle array loop through that array(userHandle one) and check if one of those values matches some string I choose called uid. How to write that code in Javascript?
Array [
Object {
"avatar": null,
"hugCount": 2,
"id": 35,
"liked": false,
"name": "fhfdhdhf",
"text": "Yoho",
"timestamp": 1610471860157,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
},
Object {
"avatar": null,
"hugCount": 1,
"id": 34,
"liked": true,
"mood": 2,
"name": "fhfdhdhf",
"text": "I'm fine today.",
"timestamp": 1607943705709,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
"userHandle": Array [
"Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
"LrIwIx9I1xQBJ7aeCSrinpEaDP53",
],
}]
Try this code:
var uid = "LrIwIx9I1xQBJ7aeCSrinpEaDP53";
yourArray.forEach(function(item, _){
return item['userHandle']?.indexOf(uid);
});
The '?' is to make sure your Object contains the 'userHandle' property
This is the function you need... and below you can see how to use it.
You need to pass the value you are looking for, and the array with the information.
function findInUserHandle(uidValue, array)
{
return array.reduce
(
(acum, current) =>
current.userHandle && current.userHandle.indexOf(uidValue) !== -1 || acum,
false
)
}
let array = [
{
"avatar": null,
"hugCount": 2,
"id": 35,
"liked": false,
"name": "fhfdhdhf",
"text": "Yoho",
"timestamp": 1610471860157,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
},
{
"avatar": null,
"hugCount": 1,
"id": 34,
"liked": true,
"mood": 2,
"name": "fhfdhdhf",
"text": "I'm fine today.",
"timestamp": 1607943705709,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
"userHandle":[
"Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
"LrIwIx9I1xQBJ7aeCSrinpEaDP53",
],
}
]
findInUserHandle('something', array) //? false
findInUserHandle('Aw8AUj1mPkON1Fd1s6LhkNETHfb2', array) //? true
findInUserHandle('mood', array) //? false
I have a JSON object like this, I wanna access the list array elements with key and value in postman.
{
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
}
]
},
"success": true,
"message": ""
}
How to separate it as Key and Value in Javascript like,
Key: id,name,mobileNo,address,city,..
Value: 53,Sonu,6543213456,Greeny Pathway,NewYork,....
First remove comma from line : "qty": null, otherwise it will cause error in json parsing.
var resultJSON = `{
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
}
]
},
"success": true,
"message": ""
}`;
var result = $.parseJSON(resultJSON);
var myList = result.data.list[0];
$.each(myList, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
you can use below codes:
const keys = Object.keys(jsonObject);
const values = Object.values(jsonObject);
But your JSON object is deep, you should flatten it and then use keys and values of Object to make them separate.
You can get using key and value separately in a array.
var a = {
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null,
}
]
},
"success": true,
"message": ""
}
var keyval = Object.keys(a.data.list[0])
console.log(keyval)
var values = Object.values(a.data.list[0])
console.log(values)
JSON objects are key value pair you cannot get the keys and values in object form as you desire but you can get both in form of arrays from this code
var key = []
var values = []
list.map(function(l){ keys = Object.getOwnPropertyNames(l);
keys.map(function(key) {values.push(l[key]);})})
Finally this works for me!(In Postman Script)
var resdata = JSON.parse(responseBody);
console.log(resdata);
key = Object.keys(resdata.data.list[0]);
console.log(key);
value =Object.values(resdata.data.list[0]);
console.log(value);
I have json response and I want to remove few object key values from it and store the edited response on other part so that I can use again.
I know by using simple javascript, but I don't have any idea in angularjs.
Json response
{
"$id": "1",
"XYZ": [],
"ABC": [
{
"$id": "41",
"ID": 1,
"Order": 0,
"Delay": 0,
"Name": "abc",
"Count": "9",
"Storage": 3,
"Groups": []
}
],
"Projected": 2019
}
Now from this Json file I want to filter out
"$id": "41","ID": 1,"Order": 0,
"Delay": 0, "Groups": [], "Name": "abc"
So my new json structure will be like this which I want to store:
{
"$id": "1",
"XYZ": [],
"ABC": [
{
"Count": "9",
"Storage": 3
}
],
"Projected": 2019
}
Any method to achieve ?
You don't need some magic angular stuff. You can just use plain old JavaScript.
My apporach iterates through all the items in the ABC array and deletes all properties defined in the props array. Note, that this actively modifies the ABC array items.
const obj = {
"$id": "1",
"XYZ": [],
"ABC": [
{
"$id": "41",
"ID": 1,
"Order": 0,
"Delay": 0,
"Name": "abc",
"Count": "9",
"Storage": 3,
"Groups": []
}
],
"Projected": 2019
}
// Now from this Json file I want to filter out
const props = ["$id", "ID", "Order", "Delay", "Groups", "Name"];
props.forEach(prop => {
obj.ABC.forEach(abc => {
delete abc[prop];
});
});
console.log(obj);
An alternative to the other solutions.
If we have a variable called json.
This method is simple
let len = json.ABC.length;
for (let i=0;i<len;i++){
delete json.ABC[i].$id;
delete json.ABC[i].ID;
delete json.ABC[i].Order;
delete json.ABC[i].Delay;
delete json.ABC[i].Groups;
delete json.ABC[i].Name;
}
try this
let json = {
"$id": "1",
"XYZ": [],
"ABC": [
{
"$id": "41",
"ID": 1,
"Order": 0,
"Delay": 0,
"Name": "abc",
"Count": "9",
"Storage": 3,
"Groups": []
}
],
"Projected": 2019
};
json["ABC"] = json["ABC"].map(obj => ({
"Count": obj["Count"],
"Storage": obj["Storage"]
}));
// or dynamic way
let keepkeys = ["Storage", "Count"];
json["ABC"] = json["ABC"].map(obj => {
let newObj = {};
keepkeys.forEach(key => newObj[key] = obj[key]);
return newObj;
});
console.log(json)