codition statement empty or not empty - javascript

Need help to see if the array is empty or not.
what are the condition block for this?
empty array look like this:
[
{
"readTime": "2019-09-09T15:20:44.648599Z"
}
]
not empty array look like this:
[
{
"document": {
"name": "projects/warrenty-MdBQxhFSQF11ZKImqL",
"fields": {
"plate": {
"stringValue": "AW69176"
"createDate": {
"timestampValue": "2019-08-22T21:08:42.563Z"
},
"product": {
"stringValue": "Paint"
},
"exp_date": {
"timestampValue": "2026-08-22T21:08:18Z"
}
},
"createTime": "2019-08-22T21:09:19.972639Z",
"updateTime": "2019-09-09T11:33:27.134588Z"
},
"readTime": "2019-09-09T15:19:49.433613Z"
},
]

From the look of your JSON you can just check if each object's 'document' property exists.
for (var i = 0; i < array.length; i++){
if (array[i].document){
//exists
}
else { //doesn't exist}
}

You can loop through the array using forEach and can use hasOwnProperty to check if the object have any key by name document
let data = [{
"document": {
"name": "projects/warrenty-MdBQxhFSQF11ZKImqL",
"fields": {
"plate": {
"stringValue": "AW69176",
"createDate": {
"timestampValue": "2019-08-22T21:08:42.563Z"
},
"product": {
"stringValue": "Paint"
},
"exp_date": {
"timestampValue": "2026-08-22T21:08:18Z"
}
},
"createTime": "2019-08-22T21:09:19.972639Z",
"updateTime": "2019-09-09T11:33:27.134588Z"
},
"readTime": "2019-09-09T15:19:49.433613Z"
}
}, {
"readTime": "2019-09-09T15:19:49.433613Z"
}]
data.forEach((e, index) => {
if (e.hasOwnProperty('document')) {
console.log(`Object at index ${index} has document key`)
} else {
console.log(`Object at index ${index} does not have document key`)
}
})

The "empty array" as you call it is not really empty as it contains an object.
But I think what you want to do is figure out whether the array contains an object with the structure of the second array.
In order to check whether your array is "empty" as you call it, you can check wether your object has a property "document" or not.
function isEmpty(array){
var object = array[0];
return !object.hasOwnProperty('document');
}
This function will return true when your array is "empty", and false when it is not.

Related

how to loop inside object array Angular

I want to display values from my json but I don't know how to do it. Is it possible to loop inside an object array ? i don't know if the keyvalue pipe can help me but I want to do without.
how to get the student2 and also the name to display it ?
thanks everyone.
json
{
"student": {
"student1": [],
"student2": [
{
"id": "123",
"name": "boot"
},
"student3": [],
]
},
"teacher": {
"teacher1": [],
"teacher2": [
{
"id": "123456",
"name": "toto"
},
]
}
}
ts.file
get(){
this.service.getAll().subscribe((data:any) => {
object.keys(data).length > 0;
})
}
Assuming your JSON object from your GET request looks like the one you posted above simply do:
get(){
this.service.getAll().subscribe((data:any) => {
data.student.forEach(element => {
for (let key in element) {
console.log(" key:", key, "value:", element[key]);
for (let val in element[key]) {
console.log(" value:", val);
}
}
});
})
}

Trying to find element recursively in tree javascript

I'm trying to figure out how to search recursively element in json tree. For example I'm trying right now to reach 'Fruits' but can't figure out how to do it. Here's my json object
[
{
"_id": "604cab0acbdb8c1060698419",
"name": "Grocery",
"children": [
{
"children": [
{
"name": "Fruits",
"price": "200"
}
],
"_id": "604cad9b4ae51310c6f313f6",
"name": "Potatoes",
"price": "200"
},
{
"children": [],
"_id": "604cae721257d510e679a467",
"name": "Vegetables"
}
],
"date": "2021-03-13T12:07:38.186Z",
"__v": 0
} ]
function findName(name, tree) {
if(tree.children.name == name {
return tree;
}
if(tree.child == 0) {
return
}
return findName(name, tree);
};
There are a couple of issues with your implementation.
Your starting point is an array, but you treat it as though it were a node by trying to use its children property.
You're looking for name on children, but children is an array.
You're passing the same thing into findName at the end that you received. If you reach that point, you'll constantly call yourself until you run out of stack space.
Loop through the nodes in the array checking them and their children; see comments:
function findName(name, children) {
if (Array.isArray(children)) {
// Yes, check them
for (const childNode of children) {
if (childNode.name === name) {
// Found it
return childNode;
}
// Look in this node's children
const found = findName(name, childNode.children);
if (found) {
// Found in this node's children
return found;
}
}
}
}
Live Example:
const tree = [
{
"_id": "604cab0acbdb8c1060698419",
"name": "Grocery",
"children": [
{
"children": [
{
"name": "Fruits",
"price": "200"
}
],
"_id": "604cad9b4ae51310c6f313f6",
"name": "Potatoes",
"price": "200"
},
{
"children": [],
"_id": "604cae721257d510e679a467",
"name": "Vegetables"
}
],
"date": "2021-03-13T12:07:38.186Z",
"__v": 0
} ];
function findName(name, children) {
if (Array.isArray(children)) {
// Yes, check them
for (const childNode of children) {
if (childNode.name === name) {
// Found it
return childNode;
}
// Look in this node's children
const found = findName(name, childNode.children);
if (found) {
// Found in this node's children
return found;
}
}
}
}
console.log(findName("Fruits", tree));
const object = [
{
"_id": "604cab0acbdb8c1060698419",
"name": "Grocery",
"children": [
{
"children": [
{
"name": "Fruits",
"price": "200"
}
],
"_id": "604cad9b4ae51310c6f313f6",
"name": "Potatoes",
"price": "200"
},
{
"children": [],
"_id": "604cae721257d510e679a467",
"name": "Vegetables"
}
],
"date": "2021-03-13T12:07:38.186Z",
"__v": 0
} ]
function find(name, tree) {
// tree is undefined, return `undefined` (base case)
if (!tree) return
if (Array.isArray(tree)) {
// tree is an array
// so iterate over every object in the array
for (let i = 0; i < tree.length; i++) {
const obj = tree[i]
const result = find(name, obj)
// `find` returned non-undefined value
// means match is found, return it
if (result) return result
// no match found in `obj` so continue
}
} else if (tree.name === name) {
// `tree` is a key-value object
// and has matching `name`
return tree
}
// if no tree matching `name` found on the current `tree`
// try finding on its `children`
return find(name, tree.children)
}
console.log(find("Fruits", object))

How to find and replace value in JSON?

I have an object like this:
{
"responses": {
"firstKey": {
"items": {
"name": "test name one"
}
},
"anotherKey": {
"items": {
"name": "test name two"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
}
I need to find all 'name' keys and replace its value only if it starts with 'test name' then return new JSON object:
{
"responses": {
"firstKey": {
"items": {
"name": "N/A"
}
},
"anotherKey": {
"items": {
"name": "N/A"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
}
The problem is that the keys are not consistent through the objects, i.e. 'firstKey', 'secondKey'... I tried ForEach but it seems to be too cumbersome... So I need either lodash or vanila JavaScript to replace the values.
The javascript object should be iterated and then each value of name can be checked and replaced. There are checks such as hasOwnProperty() that can be used to make sure you are not iterating objects that are missing "items" or "name" for better error handling.
var data = {
"responses": {
"firstKey": {
"items": {
"name": "test name one"
}
},
"anotherKey": {
"items": {
"name": "test name two"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
};
Given the JSON above you can use a simple for statement to iterate and then check each name for some value and replace.
for(var key in data.responses){
if ((data.responses[key].items.name).match(/test name/)){
data.responses[key].items.name = "N/A";
}
}
To check your replacements you can log data to the console.
console.log(JSON.stringify(data));
It can also be done during parsing :
var json = `{
"responses": {
"firstKey": {
"items": {
"name": "test name one"
}
},
"anotherKey": {
"items": {
"name": "test name two"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
}`
var obj = JSON.parse(json, (k, v) => k == 'name' && /^test name/.test(v) ? 'N/A' : v)
console.log( obj )
A javascript object is for all intents and purposes a tree — though it can be, and may well be, a directed graph — that quite possibly may be cyclic meaning a node in the graph points back to own of its own parents. Following a cycle can result in never-ending recursion or loop.
You want to use something like traverse to do what you're talking about. It takes care of all the stuff that makes traversing a graph hassle — dealing with cycles in the graph and the like.
https://www.npmjs.com/package/traverse
https://github.com/substack/js-traverse
const traverse = require('traverse');
. . .
var scrubbed = traverse(obj).map( function(value) {
const isTestName = this.key === 'name'
&& value
&& /^test name/i.test(value)
;
if (isTestName) {
this.update('N/A');
}
});
NOTE: The callback function given to travese can't be an arrow function (() => {...} as that function's this context is the traverse context for the current node being inspected.
That traverse context also gives you access to the entire path from the root down to the current node, along with an upward link to the parent node's traverse context.
Do something like this. Convert to string replace using regex (add key to regex as well) and then convert back.
var data = {
"responses": {
"firstKey": {
"items": {
"name": "test name one"
}
},
"anotherKey": {
"items": {
"name": "test name two"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
};
var originalMsg = JSON.stringify(data);
console.log(data)
console.log(originalMsg)
var updatedMsg = originalMsg.replace(/test name [a-z]*/g, "N/A");
console.log(updatedMsg)
var newObj = JSON.parse(updatedMsg);
console.log(newObj);

cannot update an array of elements via a 2d iteration

I have two arrays of object, the first array (printerChart, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
},
....
]
The second array (items, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "hp"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do is to iterate via the second array and, if the part of the name of an item (i.e. DT8) is included in an element of the array 'compatibility' of the first array, I would like to include a new properties to it from the element of the first array: printerBrand. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
items.forEach((item) => {
printerChart.forEach((printer) => {
if (printer.compatibilty.some(compatibleElem => (
item.name.includes(compatibleElem)))) {
item.printerBrand = printer.printerBrand;
} else {
item.printerBrand = '';
}
});
});
What am I doing wrong?
You do
items.items.forEach(...)
Shouldn't you be doing
items.forEach(...)
?
I suggest to initialize item.printerBrand with an empty string and use a nested approach of some for getting a brand and to exit the loops, if found.
This prevents to get an empty string even if there is a brand to assign.
items.forEach((item) => {
item.printerBrand = '';
printerChart.some(printer => {
if (printer.compatibilty.some(compatibleElem => item.name.includes(compatibleElem))) {
item.printerBrand = printer.printerBrand;
return true;
}
});
});

How do I find the existence of a value in JSON

Say I wanted to check if Mango_EA existed. How would I do that in Node JS.
{
"selection1": [
{
"name": "ClashOnGan"
},
{
"name": "JoblessGarrett"
},
{
"name": "FemmeFatale"
},
{
"name": "Mango_EA"
}
]
}
obj.selection1.some(x => x.name === "Mango_EA")
In English,
Within the array given by obj.selection1, is there some element x which satisfies the condition that the name property of x is equal to "Mango_EA".

Categories

Resources