NodeJS could not read [Object] in JSON data - node.js

I have data as a JSON format
{"mac":"f008d155b4fe","deviceClass":["iBeacon","eddystone"],"model":"iBeacon","lastSeen":"1637655820","bevent":{"event":"update"},"rssi":{"last":-84},"beacons":[{"ibeacon":{"uuid":"783a69707094d0863b4a9bf94e555241","major":816,"minor":6,"power":0},"eddystone":{"power":0}}],"sensors":{"temperatureC":18,"voltage":3.299999952316284},"stats":{"uptime":"710","adv_cnt":"24","frame_cnt":7}},
{"mac":"a0e6f8515eff","deviceClass":["arubaTag"],"firmware":{"bankA":"1.2-15"},"assetId":"0000-0000-0000","lastSeen":"1637655821","bevent":{"event":"update"},"rssi":{"last":-69},"sensors":{"battery":83},"stats":{"uptime":"82350","frame_cnt":3},"vendorName":"Aruba"}
I can print data from the level 1 but I could not print data in another level from JSON
I would like to print value from beacons: [ [Object] ],
Please give me a hints thank you
here is my code
const data = [
{"mac":"f008d155b4fe","deviceClass":["iBeacon","eddystone"],"model":"iBeacon","lastSeen":"1637655820","bevent":{"event":"update"},"rssi":{"last":-84},"beacons":[{"ibeacon":{"uuid":"783a69707094d0863b4a9bf94e555241","major":816,"minor":6,"power":0},"eddystone":{"power":0}}],"sensors":{"temperatureC":18,"voltage":3.299999952316284},"stats":{"uptime":"710","adv_cnt":"24","frame_cnt":7}},
{"mac":"a0e6f8515eff","deviceClass":["arubaTag"],"firmware":{"bankA":"1.2-15"},"assetId":"0000-0000-0000","lastSeen":"1637655821","bevent":{"event":"update"},"rssi":{"last":-69},"sensors":{"battery":83},"stats":{"uptime":"82350","frame_cnt":3},"vendorName":"Aruba"}
];
const arr1 = data.filter(d => d.mac == "f008d155b4fe");
console.log('arr1', arr1);
for (k in arr1.beacons) {
console.log(k, ":", arr1.beacons[k]);
}

This worked for me, I made it all an object and now you can access the beacons by doing newData.devices[0].beacons[0].(property)
const newData = {"devices": [{"mac":"f008d155b4fe","deviceClass":["iBeacon","eddystone"],"model":"iBeacon","lastSeen":"1637655820","bevent":{"event":"update"},"rssi":{"last":-84},"beacons":[{"ibeacon":{"uuid":"783a69707094d0863b4a9bf94e555241","major":816,"minor":6,"power":0},"eddystone":{"power":0}}],"sensors":{"temperatureC":18,"voltage":3.299999952316284},"stats":{"uptime":"710","adv_cnt":"24","frame_cnt":7}}, {"mac":"a0e6f8515eff","deviceClass":["arubaTag"],"firmware":{"bankA":"1.2-15"},"assetId":"0000-0000-0000","lastSeen":"1637655821","bevent":{"event":"update"},"rssi":{"last":-69},"sensors":{"battery":83},"stats":{"uptime":"82350","frame_cnt":3},"vendorName":"Aruba"}]};
for (const beacon of newData.devices[0].beacons) {
console.log(beacon);
}

you are close to the solution, but arr1 is an array, so it doesn't have a 'beacon' property. Use the following instead:
const data = [
{"mac":"f008d155b4fe","deviceClass":["iBeacon","eddystone"],"model":"iBeacon","lastSeen":"1637655820","bevent":{"event":"update"},"rssi":{"last":-84},"beacons":[{"ibeacon":{"uuid":"7$
{"mac":"a0e6f8515eff","deviceClass":["arubaTag"],"firmware":{"bankA":"1.2-15"},"assetId":"0000-0000-0000","lastSeen":"1637655821","bevent":{"event":"update"},"rssi":{"last":-69},"sen$
];
const arr1 = data.filter(d => d.mac == "f008d155b4fe");
console.log('arr1', arr1);
for (k of arr1) {
console.log(k.beacons);
}

arr1 is an Array it doesn't have beacons property. If you expect it to be the only one item with the mac you should use data.find instead of data.filter. Also do not use for-in loop to iterate over arrays. You can use for-of or .forEach instead.
const data = [
{"mac":"f008d155b4fe","deviceClass":["iBeacon","eddystone"],"model":"iBeacon","lastSeen":"1637655820","bevent":{"event":"update"},"rssi":{"last":-84},"beacons":[{"ibeacon":{"uuid":"783a69707094d0863b4a9bf94e555241","major":816,"minor":6,"power":0},"eddystone":{"power":0}}],"sensors":{"temperatureC":18,"voltage":3.299999952316284},"stats":{"uptime":"710","adv_cnt":"24","frame_cnt":7}},
{"mac":"a0e6f8515eff","deviceClass":["arubaTag"],"firmware":{"bankA":"1.2-15"},"assetId":"0000-0000-0000","lastSeen":"1637655821","bevent":{"event":"update"},"rssi":{"last":-69},"sensors":{"battery":83},"stats":{"uptime":"82350","frame_cnt":3},"vendorName":"Aruba"}
];
// expecting only o1
const arr1 = data.find(d => d.mac == "f008d155b4fe");
console.log('arr1', arr1);
for (const beacon of arr1.beacons) { // use for-of or `forEach`
console.log(beacon);
}

Related

Get Date from Nested Array of Objects and set that date as an Key in Node.js

I'm using Node.js I have data like this:
const data= [
{"id":"1","date":"2022-09-07T15:56:32.279Z","req_id":"98"},
{"id":"2","date":"2022-09-08T15:48:19.075Z","req_id":"97"},
{"id":"3","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
{"id":"4","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
]
I want data in this format:
expected Output:
"2022-09-06":[
{"id":"4","date":"2022-09-06T15:48:19.073Z","req_id":"96"},
{"id":"3","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
]
"2022-09-08":[
{"id":"2","date":"2022-09-08T15:48:19.075Z","req_id":"97"}
]
"2022-09-07":[
{"id":"1","date":"2022-09-07T15:56:32.279Z","req_id":"98"}
]
Assuming the dates are always in the same format, I would do something like this:
function mapData(data){
// returns the given date as an string in the "%dd-%mm-%yyyy" format
const getDateWithoutTime = (dateString) => dateString.split("T")[0];
const mappedData = [];
for(const req of data){
const formattedDate = getDateWithoutTime(req.date);
// if the key already exists in the array, we add a new item
if(mappedData[formattedDate]) mappedData[formattedDate].push(req);
// if the key doesn't exist, we create an array with that single item for that key
else mappedData[formattedDate] = [req];
}
return mappedData;
}
Straightforward solution using regex:
let result = new Map();
for (const item of data) {
let date = item['date'].match(/\d{4}-\d{2}-\d{2}/)[0];
let items = result.get(date) || [];
items.push(item);
result.set(date, items)
}

Verify and select the right object in an array thanks to a find method which will match with a param json

I need some help,
I've got a json with some parameters inside of it, actually 2 but one day we may add some more in it.
I want to find between some object in an array the right one thanks to all parameters in the json
Am i using the right method ?
to be clearer, i want the param.t to match with the element.t, and the param.tid to match with the element.tid and if moving forward one more parameter cd1 is added to the JSON, this param.cd1 will match with element.cd1
thanks for the time !
const array1 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }
for (let [key, value] of Object.entries(param)) {
console.log(`${key}: ${value}`);
}
const obj = array1.find(element => element.t == param.t);
If I am following correctly, you want to compare an array of objects to an object and based on some keys in 'param' object you want to filter out your array1.
const array2 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param1 = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }
const test = array2.find(checkExist);
const checkExist = el => {
return el.t == param1.t && el.tid == param1.tid; // here you can add your keys in future
}

How to remove same named objects from a JSON structure, but with a non uniform pattern in structure?

I have a json structure, that is a bit odd, this is returned from a remote device, and I have to accept it as is. For example...
{"_":"e6a7f749","4321013c":{"_":"5d839a60"},"67ea44a0":{"_":"ec7500f9"},"6bea5f08":{"_":"ecdaead4"},"1e92311e":{"_":"5348dab3"}}
I need to remove the '_' key-value pairs, but retain everything else, such that...
{"4321013c":,"67ea44a0":,"6bea5f08":,"1e92311e":,}
As you can see, this leaves just some 'keys', from the original structure. I then want to convert the 'keys' to a simple array of values. Such...
["4321013c","67ea44a0","6bea5f08","1e92311e"]
All this done in node.js (JavaScript) by the way.
Here is my solution. I am not sure if I fully understood the question though.
But here I traverse the object, an gather up all the keys and values into another, flattened object. Then finally, I run Object.keys on that and remove any "_" values.
const obj = {
"_":"e6a7f749",
"4321013c":{"_":"5d839a60"},
"67ea44a0":{"_":"ec7500f9"},
"6bea5f08":{"_":"ecdaead4"},
"1e92311e":{"_":"5348dab3"}
};
const collectValues = (root) => {
return Object.keys(root).reduce((map, key) => {
const value = root[key];
if (typeof value === 'string') {
map = {
...map,
[key]: true,
[value]: true
};
} else {
const nestedValues = collectValues(root[key]);
map = {
...map,
...nestedValues,
[key]: true
};
}
return map;
}, {});
}
const uniqueArray = Object.keys(collectValues(obj)).filter(v => v !== '_');
console.log(uniqueArray);

how to check if one of the array got a value using Ramda

hi im trying to check if one of the array got a value and it need to return true
input1 = { "value": [
{
"props": {
"forest": []
}
},
{
"props": {
"forest": [
{
"items": "woods"
}
]
}
} ] }
input2 = { "value": [
{
"props": {
"forest": []
}
},
{
"props": {
"forest": []
}
} ] }
the code i tried is R.anyPass to check if one of the value is True and if yes then it return true
const forestgotwoods = R.pipe(
R.path(['value']),
R.map(R.pipe(
R.path(['props','forest']),
R.isEmpty,
R.not,
)),
R.anyPass
);
console.log(forestwoods(input1)); undef
console.log(forestwoods(input2)); undef
and I also try it this way
const forestgotwoods = R.anyPass(
[R.pipe(
R.path(['value']),
R.map(R.pipe(
R.path(['props','forest']),
R.isEmpty,
R.not,
))
)]
);
console.log(forestwoods(input1)); //true
console.log(forestwoods(input2)); //true
The result for input1 need to be true
The result for input2 need to be false
Use R.any that returns a boolean according to the predicate. R.anyPass accepts an array of predicates, which is not needed here. You can remove the R.anyPass from the start because we don't need the check here.
In addition, you need to check if any any array of props.forest is empty, so remove replace R.map with R.any.
const forestgotwoods = R.pipe(
R.prop('value'), // get the value array
R.any(R.pipe( // if predicate returns true break and return true, if not return false
R.path(['props', 'forest']), // get the forest array
R.isEmpty,
R.not,
))
)
const input1 = {"value":[{"props":{"forest":[]}},{"props":{"forest":[{"items":"woods"}]}}]}
const input2 = {"value":[{"props":{"forest":[]}},{"props":{"forest":[]}}]}
console.log(forestgotwoods(input1)); // true
console.log(forestgotwoods(input2)); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
Another option is to use R.all to check if all are empty, and then use R.not to negate the result of R.all:
const forestgotwoods = R.pipe(
R.prop('value'), // get the value array
R.all(R.pipe( // if predicate returns true for all, return true, if at least one returns false, return false
R.path(['props', 'forest']), // get the forest array
R.isEmpty,
)),
R.not // negate the result of R.all
)
const input1 = {"value":[{"props":{"forest":[]}},{"props":{"forest":[{"items":"woods"}]}}]}
const input2 = {"value":[{"props":{"forest":[]}},{"props":{"forest":[]}}]}
console.log(forestgotwoods(input1)); // true
console.log(forestgotwoods(input2)); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
Using my 2nd solution with R.propSatisfies (suggested by #Hitmands) generates a short and readable solution:
const forestgotwoods = R.pipe(
R.prop('value'), // get the value array
R.all(R.pathSatisfies(R.isEmpty, ['props', 'forest'])), // if all are empty, return true, if at least one return is not, return false
R.not // negate the result of R.all
)
const input1 = {"value":[{"props":{"forest":[]}},{"props":{"forest":[{"items":"woods"}]}}]}
const input2 = {"value":[{"props":{"forest":[]}},{"props":{"forest":[]}}]}
console.log(forestgotwoods(input1)); // true
console.log(forestgotwoods(input2)); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
I think this is a simpler, more readable Ramda approach:
const forestHasWoods = where ({
value: any (hasPath (['props', 'forest', 0]))
})
const input1 = {value: [{props: {forest: []}}, {props: {forest: [{items: "woods"}]}}]};
const input2 = {value: [{props: {forest: []}}, {props: {forest: []}}]};
console.log (forestHasWoods (input1))
console.log (forestHasWoods (input2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
<script> const {where, any, hasPath} = R </script>
where is used to turn a description of an object into a predicate, especially useful in filtering. any has been discussed in other answers, and is definitely what you want here rather than anyPass. And hasPath reports whether three is a value to be found at this path in the given object..
There is a potential issue here, I suppose. If you are dealing with sparse arrays -- well if you are, you're already in a state of sin -- but if you are, then forest could have a value but not one at index 0. If this is the case, you might prefer a version like this:
const forestHasWoods = where ({
value: any (pathSatisfies (complement (isEmpty), ['props', 'forest']))
})
Similarly to the previous answer from #Ori Drori,
you could also leverage R.useWith to create a function that operates on both arrays...
const whereForestNotEmpty = R.pathSatisfies(
R.complement(R.isEmpty),
['props', 'forest'],
);
const findForest = R.pipe(
R.propOr([], 'value'),
R.find(whereForestNotEmpty),
);
const find = R.useWith(R.or, [findForest, findForest]);
// ===
const a = {
"value": [
{"props":{"forest":[]}},
{"props":{"forest":[{"items":"woods"}]}}
]
}
const b = {
"value": [
{"props":{"forest":[]}},
{"props":{"forest":[]}}
]
}
console.log(find(a, b));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
Note: use R.complement to negate predicates

Using Node.js iterating array of object and if value matched then insert all related values in different array

INPUT
[
{"Id":1,"text":"Welcome","question":"san","translation":"willkommen."},
{"Id":1,"text":"Welcome","question":"se","translation":"bienvenida"},
{"Id":1,"text":"Welcome","question":"fr","translation":"propriétaires"},
{"Id":1,"text":"ajax","question":"san","translation":"ommen."},
{"Id":1,"text":"ajax","question":"se","translation":"bienve"},
{"Id":1,"text":"ajax","question":"fr","translation":"propires"}
]
if question = san then all "san" objects will be inserted in array like and so on-
san:[{"text":"Welcome","question":"san","translation":"willkommen.},
{"text":"ajax","question":"san","translation":"ommen."},
se:[{"text":"Welcome","question":"se","translation":"bienvenida.},
{"text":"ajax","question":"se","translation":"bienve."},
fr:[{"text":"Welcome","question":"fr","translation":"propriétaires.},
{"text":"ajax","question":"fr","translation":"propires."},
Question is how do i check if question=san then make one array and insert all san values in it and so on without hardcoding the question property values.
Tried looping things but how to match without hardcoding because in future question attribute can change .
question="san" will be all together in an array "se" will be all together in an array and so on.
New to this not know much about nodejs.
Tried something like this but not coming as required way
fs.readFile('./data.json', 'utf8', function (err,data) {
data = JSON.parse(data);
var array = [];
for(var i = 0; i < data.length; i++) {
var lang = data[i].language;
for(var j= 0; j< data.length; j++) {
if(lang == data[j].language){
array.push(data[j].language);
array.push(data[j].translation);
array.push(data[j].text);
}
}
}
output Required
san:[{"text":"Welcome","question":"san","translation":"willkommen.},
{"text":"ajax","question":"san","translation":"ommen."},
se:[{"text":"Welcome","question":"se","translation":"bienvenida.},
{"text":"ajax","question":"se","translation":"bienve."},
fr:[{"text":"Welcome","question":"fr","translation":"propriétaires.},
{"text":"ajax","question":"fr","translation":"propires."},
I recommend you to use ES6 functions instead of for. You can separate the different processes and make the code more modular and declarative. This way you can change easily the desired output since your code is made by little pieces.
const data = [
{"Id":1,"text":"hi all present ","language":"sde","translation":"Hernjd ndjjsjdj"},
{"Id":1,"text":"hi all present","language":"ses","translation":"dfks kdfk kdfk"},
{"Id":1,"text":"hi all present","language":"sfr","translation":"bsh kkoweofeo"},
{"Id":1,"text":"hi all present","language":"szh","translation":"kdijo keow"},
{"Id":1,"text":"activated","language":"sde","translation":"Konto eid ke"},
{"Id":1,"text":"activated","language":"ses","translation":"La cueweffewfefwef."},
{"Id":1,"text":"activated","language":"sfr","translation":"Cowefrwef"},
{"Id":1,"text":"activated","language":"szh","translation":"fhewjhfwh"},
{"Id":1,"text":"completed","language":"sde","translation":"Ihr fwejiewf"},
{"Id":1,"text":"completed","language":"ses","translation":"Ya hfuwifrw"},
{"Id":1,"text":"completed","language":"sfr","translation":"Votrkwfwe"},
{"Id":1,"text":"completed","language":"szh","translation":"dmksfkwkf"},
{"Id":1,"text":"ACTION","language":"sde","translation":"AKTION"},
{"Id":1,"text":"ACTION","language":"ses","translation":"ACCIONES"},
{"Id":1,"text":"ACTION","language":"fr","translation":"ACTION"}];
// Define the properties that we want to filter for each element
const filterProperties = (item) => ({
text:item.text,
language: item.language,
translation:item.translation
})
// Given a type of languages ('sde'), filter the data in function of this value
const getItemsByLanguage = (language) => {
return data.filter((item) => item.language === language)
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
// Get the unique values of languages: ['sde', 'ses', 'sfr', ...]
const uniqueLanguages = data.map((item) => item.language).filter(onlyUnique)
// Get all found items for a language ('sde') and get the desired format (returns array of objects)
const resultArray = uniqueLanguages.map((language) => (
{[language]: getItemsByLanguage(language).map(filterProperties)}
))
// Convert the array of objects to single object
const result = Object.assign({}, ...resultArray)
console.log(result)
const data = [
{"Id":1,"text":"hi all present ","language":"sde","translation":"Hernjd ndjjs
jdj"},
{"Id":1,"text":"hi all present","language":"ses","translation":"dfks kdfk
kdfk"},
{"Id":1,"text":"hi all present","language":"sfr","translation":"bsh kkowe
ofeo"},
{"Id":1,"text":"hi all present","language":"szh","translation":"kdijo keow"},
{"Id":1,"text":"activated","language":"sde","translation":"Konto eid ke"},
{"Id":1,"text":"activated","language":"ses","translation":"La cueweffewfef
wef."},
{"Id":1,"text":"activated","language":"sfr","translation":"Cowefrwef"},
{"Id":1,"text":"activated","language":"szh","translation":"fhewjhfwh"},
{"Id":1,"text":"completed","language":"sde","translation":"Ihr fwejiewf"},
{"Id":1,"text":"completed","language":"ses","translation":"Ya hfuwifrw"},
{"Id":1,"text":"completed","language":"sfr","translation":"Votrkwfwe"},
{"Id":1,"text":"completed","language":"szh","translation":"dmksfkwkf"},
{"Id":1,"text":"ACTION","language":"sde","translation":"AKTION"},
{"Id":1,"text":"ACTION","language":"ses","translation":"ACCIONES"},
{"Id":1,"text":"ACTION","language":"fr","translation":"ACTION"}];
// Define the properties that we want to filter for each element
const filterProperties = (data) => ({
text:data.text,
question: data.question,
translation:data.translation
})
// Given a type of question ('san'), filter the data in function of this value
const getQuestions = (question) => {
return data.filter((item) => item.question === question)
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
// Get the unique values of questions: ['san', 'se', 'fr']
const uniqueQuestions = data.map((item) => item.question).filter(onlyUnique)
// Get all found values for a question and get the desired format (returns
array of objects)
const resultArray = uniqueQuestions.map((question) => (
{[question]: getQuestions(question).map(filterProperties)}
))
// Convert the array of objects to single object
const result = Object.assign({}, ...resultArray)
console.log(result)

Resources