Compare single object across JSON array nodeJS - javascript

If I have the below json data for example, how would I compare this array to return true based on a single element of the array?
In this example, Id like true to be returned as the url's are all the same, ignoring all other objects. However if one of the url's were different false should be returned.
[
{
id: 1,
name: "a",
url: "http://www.google.co.uk"
},
{
id: 2,
name: "b",
url: "http://www.google.co.uk"
},
{
id: 3,
name: "c",
url: "http://www.google.co.uk"
}
]
I have tried to use a filter to take only the url object and then compare that, however that hasn't worked.
Thanks for any suggestions

I think you could use the "every" method to check that.
You could get the url of the first position and check with that if the whole array satisfy your condition.
const firstUrl = yourArray[0].url;
const allUrlsAreTheSame = yourArray.every(item => item.url === firstUrl);

It's not nearly as elegant as the .every() approach, but it's good to show different ways of approaching array iterations
const data = [{
id: 1,
name: "a",
url: "http://www.google.co.uk"
},
{
id: 2,
name: "b",
url: "http://www.google.co.uk"
},
{
id: 3,
name: "c",
url: "http://www.google.co.uk"
}
]
function urlsAreIdentical(arr) {
let theurl, urlsAreTheSame = true;
arr.forEach(obj => {
if (!theurl) theurl = obj.url;
else if (theurl != obj.url) urlsAreTheSame = false;
})
return urlsAreTheSame;
}
console.log(urlsAreIdentical(data));
data.push({
id: 4,
name: "c",
url: "http://www.yahoo.co.uk"
});
console.log(urlsAreIdentical(data));

Related

Conditionally combine arrays of objects based on Ids

How can I add the status property from object2 into object1 based on newEmployeeId matching employeeId only if the dependentId is NULL.
For example: An array where Ben, Jim and Dan have statuses of Complete, Updating and Finished, respectively. Lauren should not have a status.
var object1 = [
{ name: 'Ben', employeeId: 1, dependentId: null },
{ name: 'Lauren', employeeId: 1, dependentId: 5},
{ name: 'Jim', employeeId: 2, dependentId: null },
{ name: 'Dan', employeeId: 3, dependentId: null}
];
var object2 = [
{ status: 'Complete', newEmployeeId: 1 },
{ status: 'Updating', newEmployeeId: 2 },
{ status: 'Finished', newEmployeeId: 3 }
];
There are a number of ways to approach this. Here's one:
object1.forEach(o1 => {
if (o1.dependentId !== null) return;
const o2 = object2.find(o2 => o2.newEmployeeId === o1.employeeId);
if (!o2) return;
o1.status = o2.status;
})
The idea is that we loop over each entry of object1 via the forEach() array method. For each such entry o1, we first check to make sure that its dependentId is null (because you only want to operate on such entries) and give up if it isn't.
Then we search the object2 array for a matching entry o2 via the find() array method. If no such entry is found, o2 will be undefined and we we give up. Otherwise we set o1's status property to match that of o2.
For the example code you gave, this produces the following final state for object1:
console.log(object1);
/* [{
"name": "Ben",
"employeeId": 1,
"dependentId": null,
"status": "Complete"
}, {
"name": "Lauren",
"employeeId": 1,
"dependentId": 5
}, {
"name": "Jim",
"employeeId": 2,
"dependentId": null,
"status": "Updating"
}, {
"name": "Dan",
"employeeId": 3,
"dependentId": null,
"status": "Finished"
}] */
Note that, depending on your use cases, you might want to change the implementation. For example, if your arrays have many entries, you might want to index object2 by newEmployeeId ahead of time instead of finding its elements over and over again. But that's outside the scope of the question as asked.
Playground link to code
Try this:
object1.forEach(item => {
if (!item.dependentId) {
result = object2.find(item2 => item2.newEmployeeId === item.employeeId)
item.status = result.status
}
})

Javascript: How to iterate through an array looking for an object value?

I have a js file that is just a an array with the name and type of person. I am trying to write a function in my other file to iterate through that array of objects and return just the object that matches a certain criteria. Here is my code.
person.js
export const persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
utils.js
// params initialized already
person_type = params.subType
const name = persons_options.map((option) => {
if(person_type === option.type){
return option.name
}
})
const person = name
The issue is I know map creates a new array so the output is ,,Phil. How would I just return one of the object names instead of all of them.
find() will do the work
let persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
let obj = persons_options.find(o => o.type === 'Developer');
//to return name
console.log("name",obj.name);
console.log(obj);
You need to use the find function.
See here the list of functions that you can call on an array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods
filter might best suit your case if multiple results may be returned.

How to convert an array of URLs into a tree/folder structure data?

For start I have an array of URLs which I have crawled using a simple-crawler library.
The data received is what I want to transform into a tree structure or folder structure.
I am using react-tabulator here because I wanted to resize columns of table.
Now along with normal table, I want to have the nested folder view structure.
//input data
const urls = [
{ id: 1, address: 'https://happy.com' },
{ id: 2, address: 'https://happy.com/about' },
{ id: 3, address: 'https://happy.com/contact' },
{ id: 4, address: 'https://happy.com/contact/office' },
{ id: 5, address: 'https://happy.com/contact/home' },
{ id: 6, address: 'https://happy.com/projects' },
];
//output data
tableDataNested = [
{ id: 1, address: 'https://happy.com',
_children:[
{ id: 2, address: 'https://happy.com/about', _children:[] },
{ id: 3, address: 'https://happy.com/contact',
_children:[
{ id: 4, address: 'https://happy.com/contact/office', _children:[] },
{ id: 5, address: 'https://happy.com/contact/home', _children:[] },
]
},
{ id: 6, address: 'https://happy.com/projects', _children:[] },
]
}
];
Though I saw 1-2 posts resembling this concept, I wasn’t sure on the pure JS way of doing or probably use some nice libraries too.
Any insights anyone?
You can just split the URL-s along the last slash (there always will be one here because of the //: part) and use a Map to track containment relations:
const urls = [
{ id: 1, address: 'https://happy.com' },
{ id: 2, address: 'https://happy.com/about' },
{ id: 3, address: 'https://happy.com/contact' },
{ id: 4, address: 'https://happy.com/contact/office' },
{ id: 5, address: 'https://happy.com/contact/home' },
{ id: 6, address: 'https://happy.com/projects' },
];
const tableDataNested = [];
const prefixmap = new Map();
for(let url of urls) {
url._children = []; // extend node with the array
let address = url.address;
let lastslash = address.lastIndexOf('/');
let prefix = address.substring(0,lastslash);
if(prefixmap.has(prefix)) { // has parent, so add to that one
prefixmap.get(prefix)._children.push(url)
} else { // toplevel node
tableDataNested.push(url);
}
prefixmap.set(address,url); // store as potential parent in any case
}
console.log(tableDataNested);
This snippet actually modifies the original objects (in urls), but of course it's also possible to make a copy if needed, something like
url = {id:url.id,address:url.address,_children:[]};
instead of url._children = [];
Before I answer this question, I must give a fair warning that this question is broad and moderators usually flag them.
Luckily, the solution that you're looking for is alsocalled a "tree" in UI design terminologies. I found a few:
https://material-ui.com/components/tree-view/
The catch here is, you've to use material-ui library for this (my assumption)
https://reactjsexample.com/a-hierarchical-object-tree-component-for-react/
This one has a github page too & a codesandbox live working example too
Another, https://reactjsexample.com/a-themable-and-configurable-treeview-for-react/
Hope, this helps.

How can i display more than one array elements that satisfy a condition?

How can I display multiple values of an array to the console that match the condition (e.g: === "McDonalds")?
I only managed to display one item. But I don't know how i can display all the value of my array.
public products: product[] = [
{ id: 1, name: "McFlurry", price: 2, enseigne:"McDonalds" },
{ id: 2, name: "Potatoes", price: 3, enseigne:"McDonalds" },
{ id: 3, name: "BigMac", price: 4, enseigne:"KFC" },
{ id: 4, name: "Nuggets", price: 3, enseigne:"KFC" }
];
searchEnseigne(){
let server = this.products.find(x => x.enseigne === "McDonalds");
console.log(server);
}
let server = this.products.filter(x => x.enseigne === "McDonalds");
console.log(server);
Use filter instead of find:
The filter() method creates a new array with all elements that pass the test. While The find() method returns the value of the first element
searchEnseigne(){
let server = this.products.filter(x => x.enseigne === "McDonalds");
console.log(server);
}

Javascript - how to get just the value of the property after filtering and mapping the array of objects

I am filtering and mapping the array objects that looks like this:
taxonomy:Object
data:Array[2]
0:Object
id:377
name:"Buss"
slug:"buss"
type:"post_tag"
1:Object
My function looks like this:
let tag = this.article.taxonomy.data.filter(function( data ) {
return data.type.includes('tag')
}).map(function(obj) {
return obj.name;
});
return tag;
What I am just wondering is there a way to get from the map function just the string name value, since now it returns ["Buss"], so that don't need to use the index at the end of the function:
return tag[0]
It sounds like you want find, not filter, if you're looking only for one result. find returns the first entry for which the callback returns a truthy value, or undefined if it never does. So:
const obj = this.article.taxonomy.data.find(data => data.type.includes('tag'));
const tag = obj && obj.name; // Note the guard in case no entry matched
return tag; // Will be the name or `undefined`
(Note that I've assumed you can use an arrow function, as you're using let. If not, just replace it with a function function.)
Live Example:
const taxonomy = {
data: [
{
id: 375,
name: "A",
slug: "A",
type: "nope"
},
{
id: 376,
name: "B",
slug: "B",
type: "nor-this"
},
{
id: 377,
name: "Buss",
slug: "buss",
type: "post_tag"
},
{
id: 378,
name: "C",
slug: "C",
type: "blah"
}
]
};
const obj = taxonomy.data.find(data => data.type.includes('tag'));
const tag = obj && obj.name;
console.log(tag);

Categories