Getting data with a similar key name in JavaScript - javascript

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);

Related

How do I set value of nested object to key of current object?

This array has the key to substitute with nested key of 'name'
const arr = ['status', 'user', ...] <-- This array contains key to be replaced with name
This is what my current response object is
[
{
"id": 11,
"location": "Mumbai",
"status": {
"name": "NEW"
},
"user": {
"name": "Rakesh"
}
}
]
How do I modify the above array of objects to this below
[
{
"id": 11,
"location": "Mumbai",
"status": "NEW",
"user": "Rakesh"
}
]
can try below code
const keys = ['status', 'user']
let arr = [
{
"id": 11,
"location": "Mumbai",
"status": {
"name": "NEW"
},
"user": {
"name": "Rakesh"
}
}
]
arr.map(a => keys.forEach(k => {
if(a[k] && a[k].name) a[k] = a[k].name
}));
console.log(arr);
I'd try this one:
const results = [
{
"id": 11,
"location": "Mumbai",
"status": {
"name": "NEW"
},
"user": {
"name": "Rakesh"
}
}, {
"id": 12,
"location": "Helsinki",
"status": {
"name": "NEW"
},
"user": {
"name": "Samuli"
}
}
];
const flattenObject = ([key, value]) => ((typeof value === 'object') ? {[key] : value[Object.keys(value)[0]]} : {[key]: value});
const reduceToSingleObject = (acc, b) => ({...acc, ...b});
const actualResults = results.map((result) => Object.entries(result).map(flattenObject).reduce(reduceToSingleObject));
console.log(actualResults);
Explanation:
flattenObject is a function to flatten structure of object inside object. This only takes the first prop (without knowing the name of the key). If you, for some reason, would need to flatten several key-values, then it'd need whole different kind of helper function to sort that out.
reduceToSingleObject is a function to put all the key-value pairs into a single object. This could have been done already in flattenObject function, but for the clarity, I separated it to a normal map - reduce pattern.
actualResults is the outcome where we go through all the entries of your original results.

How to change key name of an object by comparing another object?

I have an array of object and another object containing labels, how to write a simple function to compare both array and replace the key name.
input = [
{
"id": "AAP",
"prd": "PL",
"trcode": "NORTH",
"accountNo": "12345",
"prBranch": null,
"prDealer": "Dealer 1",
"prUser": "CFG",
"staticBranch": "YES",
"staticCustomer": "NO",
"reason": "Invalid request"
},
{
"id": "AAC",
"prd": "PL",
"trcode": "WEST",
"accountNo": "67890",
"prBranch": null,
"prDealer": "Dealer 2",
"prUser": "DFG",
"staticBranch": "YES",
"staticCustomer": "NO",
"reason": "Invalid request"
}
],
labels = [
{
"key": "id",
"value": "USER"
},
{
"key": "prd",
"value": "PRODUCT"
},
{
"key": "trcode",
"value": "TRANSFER_CODE"
},
{
"key": "accountNo",
"value": "ACCOUNT_NUMBER"
},
{
"key": "prBranch",
"value": "PROCESSING_BRANCH"
},
{
"key": "prDealer",
"value": "PROCESSING_DEALER"
},
{
"key": "prUser",
"value": "PROCESSING_USER"
},
{
"key": "staticBranch",
"value": "STATIC_BRANCH"
},
{
"key": "staticAgent",
"value": "STATIC_AGENT"
},
{
"key": "reason",
"value": "Reason"
}
]
Expected output =
[
{
"USER": "AAP",
"PRODUCT": "PL",
"TRANSFER_CODE": "NORTH",
"ACCOUNT_NUMBER": "12345",
"PROCESSING_BRANCH": null,
"PROCESSING_DEALER": "Dealer 1",
"PROCESSING_USER": "CFG",
"STATIC_BRANCH": "YES",
"STATIC_CUSTOMER": "NO",
"Reason": "Invalid request"
},
{
"USER": "AAC",
"PRODUCT": "PL",
"TRANSFER_CODE": "WEST",
"ACCOUNT_NUMBER": "67890",
"PROCESSING_BRANCH": null,
"PROCESSING_DEALER": "Dealer 2",
"PROCESSING_USER": "DFG",
"STATIC_BRANCH": "YES",
"STATIC_CUSTOMER": "NO",
"Reason": "Invalid request"
}
],
You can use Array#map to convert each object in the array. For each object, we can map over the entries of the object and use Array#find to look for the replacement key if it exists. Finally, Object.fromEntries converts the array of key-value pairs back to an object.
let input=[{id:"AAP",prd:"PL",trcode:"NORTH",accountNo:"12345",prBranch:null,prDealer:"Dealer 1",prUser:"CFG",staticBranch:"YES",staticCustomer:"NO",reason:"Invalid request"},{id:"AAC",prd:"PL",trcode:"WEST",accountNo:"67890",prBranch:null,prDealer:"Dealer 2",prUser:"DFG",staticBranch:"YES",staticCustomer:"NO",reason:"Invalid request"}],labels=[{key:"id",value:"USER"},{key:"prd",value:"PRODUCT"},{key:"trcode",value:"TRANSFER_CODE"},{key:"accountNo",value:"ACCOUNT_NUMBER"},{key:"prBranch",value:"PROCESSING_BRANCH"},{key:"prDealer",value:"PROCESSING_DEALER"},{key:"prUser",value:"PROCESSING_USER"},{key:"staticBranch",value:"STATIC_BRANCH"},{key:"staticAgent",value:"STATIC_AGENT"},{key:"reason",value:"Reason"}];
const res = input.map(o =>
Object.fromEntries(Object.entries(o)
.map(([k,v])=>[labels.find(({key})=>key===k)?.value ?? k, v])));
console.log(res)
.as-console-wrapper{max-height:100%!important;top:0}
Loop through input and inside the loop use a for...in loop to loop through each property.
Inside the loop, loop through labels and get the corresponding value to that property, set the value of the property to the new property and delete the previous property.
input.forEach(e => {
for (const l in e) {
var a;
labels.forEach(e => {
e.key == l && (a = e.value)
}), e[a] = e[l], delete e[l]
}
});
Demo:
input=[{id:"AAP",prd:"PL",trcode:"NORTH",accountNo:"12345",prBranch:null,prDealer:"Dealer 1",prUser:"CFG",staticBranch:"YES",staticCustomer:"NO",reason:"Invalid request"},{id:"AAC",prd:"PL",trcode:"WEST",accountNo:"67890",prBranch:null,prDealer:"Dealer 2",prUser:"DFG",staticBranch:"YES",staticCustomer:"NO",reason:"Invalid request"}];var labels=[{key:"id",value:"USER"},{key:"prd",value:"PRODUCT"},{key:"trcode",value:"TRANSFER_CODE"},{key:"accountNo",value:"ACCOUNT_NUMBER"},{key:"prBranch",value:"PROCESSING_BRANCH"},{key:"prDealer",value:"PROCESSING_DEALER"},{key:"prUser",value:"PROCESSING_USER"},{key:"staticBranch",value:"STATIC_BRANCH"},{key:"staticAgent",value:"STATIC_AGENT"},{key:"reason",value:"Reason"}];
input.forEach(e=>{for(const l in e){var a;labels.forEach(e=>{e.key==l&&(a=e.value)}),e[a]=e[l],delete e[l]}});
console.log(input);
One of the first thing I would to is to use an object instead of an array for your key association:
labels = {
"id": "USER",
"prd": "PRODUCT",
"trcode": "TRANSFER_CODE",
"accountNo": "ACCOUNT_NUMBER",
"prBranch": "PROCESSING_BRANCH",
"prDealer": "PROCESSING_DEALER",
"prUser": "PROCESSING_USER",
"staticBranch": "STATIC_BRANCH",
"staticAgent": "STATIC_AGENT",
"reason": "Reason"
}
Now if you want to map them to your new object you can do
function renameKeys(src) {
let entries = Object.entries(src)
let renamedEntries = entries.map(([key, value]) => [
labels[key] || key,
/* I added a fallback to the original key
if it's not found to avoid undefined keys */
value,
])
return Object.fromEntries(renamedEntries)
}
// and use it like so
console.log(input.map(renameKeys))
You can just iterate them and assign the values as below
for (var object of input) {
for (var mapping of labels) {
if (object[mapping.key] !== undefined) {
object[mapping.value] = object[mapping.key];
delete object[mapping.key];
}
}
}
console.log(input);
The way I'd do it would be:
const input = [{
"id": "AAP",
"prd": "PL",
"trcode": "NORTH",
"accountNo": "12345",
"prBranch": null,
"prDealer": "Dealer 1",
"prUser": "CFG",
"staticBranch": "YES",
"staticCustomer": "NO",
"reason": "Invalid request"
},
{
"id": "AAC",
"prd": "PL",
"trcode": "WEST",
"accountNo": "67890",
"prBranch": null,
"prDealer": "Dealer 2",
"prUser": "DFG",
"staticBranch": "YES",
"staticCustomer": "NO",
"reason": "Invalid request"
}
];
const labels = [{
"key": "id",
"value": "USER"
},
{
"key": "prd",
"value": "PRODUCT"
},
{
"key": "trcode",
"value": "TRANSFER_CODE"
},
{
"key": "accountNo",
"value": "ACCOUNT_NUMBER"
},
{
"key": "prBranch",
"value": "PROCESSING_BRANCH"
},
{
"key": "prDealer",
"value": "PROCESSING_DEALER"
},
{
"key": "prUser",
"value": "PROCESSING_USER"
},
{
"key": "staticBranch",
"value": "STATIC_BRANCH"
},
{
"key": "staticAgent",
"value": "STATIC_AGENT"
},
{
"key": "reason",
"value": "Reason"
}
]
// 1. create an object mapping the old labels to the new ones
const betterLabels = labels.reduce((outObj, item) => {
outObj[item.key] = item.value;
return outObj;
}, {});
// 2. use `Array.prototype.map` to traverse the input array
// and `Array.prototype.reduce` with the label mapping object
// to generate the output array
const output = input.map(item => {
return Object.entries(item).reduce((newItem, [key, value]) => {
betterLabels[key]
? newItem[betterLabels[key]] = value
: newItem[key] = value
return newItem
}, {});
});
//test
console.log(output);

Turn array of objects into array of unique combinations of its properties

I have to extract specific data from an object. My code works but I wonder if I could improve it by using method like map or filter.
This is for no specific background just for personnel training. Also I am using Lodash library
function extractApi(data) {
var arrayOfTowns = [];
var arrayOfCityCode = [];
var result = [];
//looping throw the expected datas (cities and postcode)
for (var i = 0; i < data.features.length; i++) {
arrayOfCityCode.push(_.toString(data.features[i].properties.postcode));
arrayOfTowns.push(_.toString(data.features[i].properties.city));
//verify unique cities
arrayOfTowns = _.uniq(arrayOfTowns);
//pushing to a new array to have the expected result format
if (arrayOfTowns[i] != undefined && arrayOfCityCode != undefined){
result[i] = arrayOfCityCode[i] + " " + arrayOfTowns[i]
}
}
return result
}
//example with some datas
extractApi( {
"type": "FeatureCollection",
"limit": 20,
"version": "draft",
"licence": "ODbL 1.0",
"attribution": "BAN",
"features": [
{
"type": "Feature",
"properties": {
"importance": 0.6466,
"type": "municipality",
"adm_weight": 4,
"postcode": "43000",
"context": "43, Haute-Loire, Auvergne-Rhône-Alpes (Auvergne)",
"id": "43157",
"population": 18.8,
"x": 769600,
"y": 6438600,
"name": "Le Puy-en-Velay",
"citycode": "43157",
"label": "Le Puy-en-Velay",
"city": "Le Puy-en-Velay",
"score": 0.8769636363636364
},
"geometry": {
"coordinates": [
3.883955,
45.043141
],
"type": "Point"
}
},
{
"type": "Feature",
"properties": {
"importance": 0.0867,
"type": "municipality",
"adm_weight": 1,
"postcode": "43000",
"context": "43, Haute-Loire, Auvergne-Rhône-Alpes (Auvergne)",
"id": "43089",
"population": 3.6,
"x": 767600,
"y": 6438900,
"name": "Espaly-Saint-Marcel",
"citycode": "43089",
"label": "Espaly-Saint-Marcel",
"city": "Espaly-Saint-Marcel",
"score": 0.8260636363636362
},
"geometry": {
"coordinates": [
3.858597,
45.046041
],
"type": "Point"
}
},
],
"query": "43000"
}
)
The goal is to receive all data.features.properties.postcode and data.features.properties.city and push it to an array. For this example the expected result is ["43000 Le Puy-en-Velay", "43000 Espaly-Saint-Marcel"]. Cities in the result should be unique.
You can indeed use .map to get the results you desire:
const parsedCities = data.features
.map(f => `${f.properties.postcode} ${f.properties.city}`)
.filter((f, i, a) => a.indexOf(f) === i);
//["43000 Le Puy-en-Velay", "43000 Espaly-Saint-Marcel"]
You can find the documentation on Array.prototype.map() here.
One may use
Array.prototype.map() to extract necessary properties (citycode, city) into the string
Set to get rid of duplicates
const src = {"type":"FeatureCollection","limit":20,"version":"draft","licence":"ODbL 1.0","attribution":"BAN","features":[{"type":"Feature","properties":{"importance":0.6466,"type":"municipality","adm_weight":4,"postcode":"43000","context":"43, Haute-Loire, Auvergne-Rhône-Alpes (Auvergne)","id":"43157","population":18.8,"x":769600,"y":6438600,"name":"Le Puy-en-Velay","citycode":"43157","label":"Le Puy-en-Velay","city":"Le Puy-en-Velay","score":0.8769636363636364},"geometry":{"coordinates":[3.883955,45.043141],"type":"Point"}},{"type":"Feature","properties":{"importance":0.0867,"type":"municipality","adm_weight":1,"postcode":"43000","context":"43, Haute-Loire, Auvergne-Rhône-Alpes (Auvergne)","id":"43089","population":3.6,"x":767600,"y":6438900,"name":"Espaly-Saint-Marcel","citycode":"43089","label":"Espaly-Saint-Marcel","city":"Espaly-Saint-Marcel","score":0.8260636363636362},"geometry":{"coordinates":[3.858597,45.046041],"type":"Point"}},],"query":"43000"};
const uniqueCities = obj =>
[...new Set(obj.features.map(({properties:{city,citycode}}) => citycode+' '+city))]
console.log(uniqueCities(src));
.as-console-wrapper {min-height: 100%}

How to get Key and Value from JSON object in Javascript(Postman)

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);

Get first element in a for..in two dimension

i have a Json object that basicly is a array and in each array i want to iterate over the propertys, so i did something like this:
for(var x = 0;x<dados.feeds.length;x++){
for(var y in dados.feeds[x]){
console.log(dados.feeds[x][y]);
/*if(data == dataInicial){
console.log("a");
}*/
}
}
that console.log(dados.feeds[x][0]) gives me undefined, i just want the first element on each x row, how can i get it ?
json object dados
{
"channel":
{
"id": 9,
"name": "my_house",
"description": "Netduino Plus connected to sensors around the house",
"latitude": "40.44",
"longitude": "-79.996",
"field1": "Light",
"field2": "Outside Temperature",
"created_at": "2010-12-13T20:20:06-05:00",
"updated_at": "2014-02-26T12:43:04-05:00",
"last_entry_id": 6060625
},
"feeds":
[
{
"created_at": "2014-02-26T12:42:49-05:00",
"entry_id": 6060624,
"field1": "188",
"field2": "25.902335456475583"
},
{
"created_at": "2014-02-26T12:43:04-05:00",
"entry_id": 6060625,
"field1": "164",
"field2": "25.222929936305732"
}
]
}
The code as you have it runs fine, everything traces out, nothing is undefined (I tried it).
But, console.log[x][0] will trace undefined, because:
var x = 0;
var obj = feeds[x]; // this will be the first object from the feeds array.
console.log ( obj [ 0 ] );
You probably see it now; that will trace undefined, because that obj has no 0 property. It's an object with keys/values.
So this would work:
var each = 'created_at';
console.log ( obj [ each ] );
And this:
for ( var each in obj ) {
console.log ( each, obj [ each ] );
}
How is your data looks like? If it's similar to
var dados = {
feeds: [ {a: 'aa'}, {b: 'bb'} ]
}
then you can try this:
dados.feeds.forEach(feed => {
Object.keys(feed).forEach((key, index) => {
if(index === 0) { console.log(feed[key]) } // aa bb...
})
})
HTH
It should be console.log(dados.feeds[x].created_at);.
Although you shouldn't rely on Javascript object key order, here is a solution that will return the value of the first key in each entry in the feeds array;
var dados = {
"channel":
{
"id": 9,
"name": "my_house",
"description": "Netduino Plus connected to sensors around the house",
"latitude": "40.44",
"longitude": "-79.996",
"field1": "Light",
"field2": "Outside Temperature",
"created_at": "2010-12-13T20:20:06-05:00",
"updated_at": "2014-02-26T12:43:04-05:00",
"last_entry_id": 6060625
},
"feeds":
[
{
"created_at": "2014-02-26T12:42:49-05:00",
"entry_id": 6060624,
"field1": "188",
"field2": "25.902335456475583"
},
{
"created_at": "2014-02-26T12:43:04-05:00",
"entry_id": 6060625,
"field1": "164",
"field2": "25.222929936305732"
}
]
};
var con = document.getElementById('console');
for (var i = 0; i < dados.feeds.length; i++) {
var firstKey = Object.keys(dados.feeds[i])[0];
con.innerHTML += '<p>' + dados.feeds[i][firstKey] + '</p>';
}
/*
Prints;
2014-02-26T12:42:49-05:00
2014-02-26T12:43:04-05:00
*/
Here is a fiddle with the working code.

Categories