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);
Related
I have this data.
{"channel":
{
"id":*******,"name":"INA229 Measurement",
"description":"Test with INA229",
"latitude":"0.0",
"longitude":"0.0",
"field1":"Voltage",
"field2":"Current",
"field3":"Power",
"field4":"Temperature",
"created_at":"2022-04-07T08:40:24Z",
"updated_at":"2022-04-07T08:40:52Z",
"last_entry_id":3771},
"feeds":[]
}
How to take only values for field(x) keys to new data. The key of the name field(x) (field1, field2, field3 ..... field8) is dynamic and varies in the range from field1 to field8 keys. I don't know how many there will be in total, even when receiving data.
Iterate over data.channel with for/in, check to see if the key starts with the keyword and, if it does, add the value of that property to a new object using that key.
const data = { "channel": { "id": "", "name": "INA229 Measurement", "description": "Test with INA229", "latitude": "0.0", "longitude": "0.0", "field1": "Voltage", "field2": "Current", "field3": "Power", "field4": "Temperature", "created_at": "2022-04-07T08:40:24Z", "fieldTest": "Test", "updated_at": "2022-04-07T08:40:52Z", "last_entry_id": 3771 }, "feeds": [] };
const out = {};
for (const key in data.channel) {
if (key.startsWith('field')) {
out[key] = data.channel[key];
}
}
console.log(out);
Using Object#entries, get the key-value pairs of channel
Using Array#reduce, iterate over the latter while updating the resulting object
In each iteration, use String#match to check for the key format
const data = { "channel": { "id": "", "name": "INA229 Measurement", "description": "Test with INA229", "latitude": "0.0", "longitude": "0.0", "field1": "Voltage", "field2": "Current", "field3": "Power", "field4": "Temperature", "created_at": "2022-04-07T08:40:24Z", "updated_at": "2022-04-07T08:40:52Z", "last_entry_id": 3771 }, "feeds": [] };
const res = Object.entries(data.channel).reduce((acc, [key, value]) => {
if(key.match(/^field[1-8]$/)) {
acc[key] = value;
}
return acc;
}, {});
console.log(res);
For reference I have zero javascript knowledge or any coding knowledge. I typically just hook up applications via IPASS applications that don't require any coding knowledge. However, I found out I need to inject some javascript into the application in order to avoid an error message.
I have the below JSON record.
I need to get rid of the empty array (sorry... if it is not an array but an object? Like I said, no javascript knowledge).
In the below code essentially what I want is to completely delete this line, because there is nothing inside the brackets and it is causing errors:
"lineitemsdata": []
Full JSON record below for reference
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [
{
"id": "5230410841",
"type": "company_to_deal"
}
]
}
},
"dealdata": [
{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [
{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}
],
"DealOwner": [
{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}
],
"NetSuiteCustomerID": 1745
}
Item inside object is called a property. If you (for some reason) have to include the property, but don't want it to have any value you can either set it's value to null or undefined.
I suspect I'm going to get criticized for this, but here is a quick and dirty way of removing this specific problem through string replacement. The 'right' way would be to break down your json into separte objects until you get to the level where the offending object lives, remove it, then rebuild it all back. For what it's worth, here's an alternative to that
let json = {
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [{
"id": "5230410841",
"type": "company_to_deal"
}]
}
},
"dealdata": [{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}],
"DealOwner": [{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}],
"NetSuiteCustomerID": 1745
}
json = JSON.stringify(json)
let strstart = json.indexOf('"lineitemsdata":[]');
let commapos = json.lastIndexOf(',', strstart);
json = json.substr(0, commapos) + " " + json.substr(commapos + 1);
json = json.replace('"lineitemsdata":[]', '');
json = JSON.parse(json)
console.log(json)
You can use this to strip any empty lineitems arrays from your json.
Assuming the reference to your record is json
for(dealIdx in json.dealdata) {
for (resultIdx in json.dealdata[dealIdx].associations["line items"].results) {
let lineItemsData = json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
if (lineItemsData != undefined && lineItemsData.length === 0 ) {
delete json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
}
}
}
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 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)
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();