I'm confused with a complex json object, in the example bellow, how can I store in a variable the whole object that has entreprise : 'microsoft'.
clientList = {
id-1111 : {
entreprise : 'facebook',
president : 'Mark',
},
id-2222 : {
entreprise : 'microsoft',
president : 'Bill',
},
id-3333 : {
entreprise : 'apple',
president : 'Tim'
}
}
I dynamicly get, for axample, 'Microsoft', and I would like to obtain as output :
{
entreprise : 'microsoft',
president : 'Bill'
}
I know it is a basic question, but I'm struggling with that for hours.
Thanks for your help.
You can use find to find a single item from a list.
var clientList = {
"id-1111": {
entreprise : 'facebook',
president : 'Mark',
},
"id-2222" : {
entreprise : 'microsoft',
president : 'Bill',
},
"id-3333" : {
entreprise : 'apple',
president : 'Tim'
}
};
var result = Object.values(clientList).find(x => x.entreprise == "microsoft");
console.log(result);
To find all objects with a paticular enterprise, use Array.filter:
const clientList = {
"id-1111" : {
entreprise : 'facebook',
president : 'Mark',
},
"id-2222" : {
entreprise : 'microsoft',
president : 'Bill',
},
"id-3333" : {
entreprise : 'apple',
president : 'Tim'
}
};
function findClientsByEnterprise(enterprise) {
return Object.values(clientList).filter( i => i.entreprise === enterprise);
}
console.log(findClientsByEnterprise("microsoft"))
Your object has broken. Use quote in your object key.
clientList = {
'id-1111' : {
entreprise : 'facebook',
president : 'Mark',
},
'id-2222' : {
entreprise : 'microsoft',
president : 'Bill',
},
'id-3333' : {
entreprise : 'apple',
president : 'Tim'
}
};
function objectSearch(key, value,obj){
for(o in obj){
if(obj[o][key] == value){
return obj[o];
}
}
return {};
}
console.log(objectSearch('entreprise','microsoft',clientList));
if the enterprise can be used as a unique ID, you could just use it as such:
'microsft': {
enterprise: 'microsoft',
president: 'Bill'
}
but as a general rule, it is not a great practice to do this. So maintaining a structure with a list of objects with unique ID's and using find would be the best solution and best practice:
clientList = [
{
id: 'id-1111',
entreprise : 'facebook',
president : 'Mark',
},
{
id: 'id-2222',
entreprise : 'microsoft',
president : 'Bill',
},
{
id: 'id-3333',
entreprise : 'apple',
president : 'Tim'
}
}
const result = clientList.find(clientObj => clientObj.enterprise === "microsoft");
Related
I have this kind of dictionary:
INPUT
movies = {
'big' : {
actors : ['Elizabeth Perkins', 'Robert Loggia']
},
'forrest gump' : {
actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
},
'cast away' : {
actors : ['Helen Hunt', 'Paul Sanchez']
}
};
and I want to use this dictionary to get a different one. For example, I have to make a function called "moviesWithActors" that will received two arguments: "movies" and "actor". Actor could be "Tom Hanks", so when you find that he was on the movie, you don't add to the nested array, but if wasn't, you add.
OUTPUT
movies = {
'big' : {
actors : ['Elizabeth Perkins', 'Robert Loggia', 'Tom Hanks']
},
'forrest gump' : {
actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
},
'cast away' : {
actors : ['Helen Hunt', 'Paul Sanchez', 'Tom Hanks]
}
};
I do this:
for (const value of Object.values(newMovies)){
console.log(value.actors)
for (const act of value.actors){
//console.log(act)
if (act == actor) {
console.log("Ok, not add")
}else{
console.log("Here I have to add");
}
}
}
where "newMovies" is a copy of "movies" and "actor = "Tom Hanks" but I can't add to the array in actors: [ ... ]. Any suggestion? Can I use map() ?
As per the requirement what I understood is that there is an existing array of movies object and you want to assign a hero in those movies. We have to ignore if the passed hero name is already there for that movie else add that hero under that movie. If my understanding is correct, Here you go :
const movies = {
'big' : {
actors : ['Elizabeth Perkins', 'Robert Loggia']
},
'forrest gump' : {
actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
},
'cast away' : {
actors : ['Helen Hunt', 'Paul Sanchez']
}
};
function updateMoviesList(obj, heroName) {
Object.keys(obj).forEach(key => {
if (!obj[key].actors.includes(heroName)) {
obj[key].actors.push(heroName)
}
})
return obj;
}
console.log(updateMoviesList(movies, 'Tom Hanks'));
You can use Push()
Like this from docs
let sports = ['soccer', 'baseball']
let total = sports.push('football', 'swimming')
console.log(sports) // ['soccer', 'baseball', 'football', 'swimming']
console.log(total.length) // 4
To access array inside dictionary you have first to access it
movies['big']['actors'].push('New Actor')
For not be "hard coded", if you do this?
let actor = 'Tom Hanks'
for (const value of Object.values(newMovies)){
for (const act of value.actors){
if (value.actors.includes(actor)) { //Here you check if actor contains in array
console.log("Ok, not add")
}else{
console.log("Here I have to add");
value.actors.push(actor) //if not push to array
}
}
}
I was suggested to use map instead and the class Object...
function actorInMovies(movies, actor) {
let mappedObject = { ...movies};
Object.entries(movies).map(movie => {
const movieName = movie[0];
const actors = movie[1].actors;
if (!actors.includes(actor))
actors.push(actor);
mappedObject = {
...mappedObject,
[movieName]: { actors }
};
});
return mappedObject
}
function main(){
const movies = {
'big' : {
actors : ['Elizabeth Perkins', 'Robert Loggia']
},
'forrest gump' : {
actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
},
'cast away' : {
actors : ['Helen Hunt', 'Paul Sanchez']
}
};
const actor = 'Tom Hanks';
console.log(actorInMovies(movies, actor))
}
main();
I want to know which logic i should use to check every object's array of parent object contained in grand parent object
Hi guys i want to check if this value for example : "127.0.0.1" exists in this object (MyObject has like 2k objects in it)
{
"name" : MyObject
"value": [
{
"name" : "Object1",
"properties":{
"address" : [
"13.65.25.19/32",
"13.66.60.119/32",
]
}
},
{
"name" : "Object2",
"properties":{
"address" : [
"13.65.25.19/32",
"127.0.0.1",
]
}
}
]
}
Btw does include() needs to match the whole string or for example if 127.0.0.1 is like this in my object 127.0.0.1/32, i can still retrieve it even if there is a ip range ?
Your data is structured quite specifically, so you can write a custom method which you can call over and over again. It will check for a
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '127.0.0.1';
const includesAddress = (address) => {
for (const val of obj.value) {
if (val.properties.address.some((a) => address === a)) return true;
}
return false;
};
console.log(includesAddress(address));
Array.flatMap implementation
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '127.0.0.1';
const output = obj.value.flatMap(item => item.properties.address).includes(address);
console.log(output);
If you want check if the partial ip addess is included in the list, you should make use of a regex implementation.
Sample Implementation
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '13.65.25.19';
const regex = new RegExp(address, 'i')
const output = obj.value.flatMap(item => item.properties.address).filter(x => regex.test(x)).length > 0;
console.log(output);
Print a shopping list
Create a function called print Shopping List that take a list of products and print the items to the screen.
//
shopping List = [
{ item Name : 'Bread', price : 11.00 },
{ item Name : 'Milk', price : 7.00 },
{ item Name : 'Cheese', price : 19.50 }
];
This should print:
Shopping list:
* Bread # R11.00
* Milk # R7.00
* Cheese # R19.50
console.log('Shopping List:');
shoppingList.forEach(ele => {
console.log('*'+ele.ItemName+'#'+'R'+ele.price);
);
Hope this helps.
You can try the below code. Hope it helps.
const shoppingList = [{
itemName: 'Bread',
price: 11.00
},
{
itemName: 'Milk',
price: 7.00
},
{
itemName: 'Cheese',
price: 19.50
}
];
const itemsHTML = shoppingList.map(item => (
`<li>${item.itemName} # R${item.price}</li>`
))
document.write(`<ul>${itemsHTML}</ul>`);
You can simply achieve it by creating a node in the HTML DOM and create the custom string by using template string.
Demo :
const shoppingList = [
{ itemName : 'Bread', price : 11.00 },
{ itemName : 'Milk', price : 7.00 },
{ itemName : 'Cheese', price : 19.50 }
];
shoppingList.forEach(item => {
const node = document.createElement("li");
const liNode = document.getElementById('priceList').appendChild(node);
liNode.innerHTML = `${item.itemName} # R${item.price}`
});
<ul id="priceList"></ul>
Your syntax is wrong in a lot of ways. An identifier (variable name, function name, etc. — “identifier” is programming jargon for “name”) cannot contain a space in almost all programming/scripting languages. So, shopping list should be shoppingList (or shopping_list), item name should be itemName or, even better, just name. As you see in the forEach part, naming the running position item, I access the name using item.name.
const shoppingList = [
{ name: 'Bread', price: 11.00 },
{ name: 'Milk', price: 7.00 },
{ name: 'Cheese', price: 19.40 },
];
shoppingList.forEach(item => {
console.log(item.name + " # R" + item.price.toFixed(2));
})
Recently, I've been learning on how to retrieve objects from an array and I've had my fair share of converting an array of objects into a singular object of objects, but I couldn't wrap my head around this one!
dataOfCars.js:
const dataOfCars = [
{
id: "car1",
owner: { license: "license001", name: "driver1" },
mechanic: [
{
id: "mechanic1",
owner: { license: "license001", name: "driver2" }
}
]
},
{
id: "car2",
owner: { license: "license021", name: "driver2" },
mechanic: []
},
{
id: "car3",
owner: { license: "license002", name: "driver2" },
mechanic: [
{
id: "mechanic1",
owner: { license: "license002", name: "driver2" }
}
]
}
];
module.exports = dataOfCars;
I know there are several examples in regards to this but the output I'm expecting is quite different as it involves nested objects:
{
cars : {
idOrder : {
"car1" : {
id : "car1",
owner : "owner1",
mechanic : ["mechanic1", "mechanic2"]
},
...
},
result : ["car1", "car2", ...]
},
mechanics : {
idOrder : {
"mechanic1" : {
id : "mechanic1",
owner : "driver2",
},
...
},
result : ["mechanic1", ...]
},
owners : {
idOrder : {
"driver1" : {
license : "license001",
name: "driver1",
},
...
},
result : ["driver1", "driver2", ...]
}
}
I gave it a go at Sandbox: https://codesandbox.io/s/old-morning-hx9m1. I used Object.assign({}, ...dataOfCars) but it only 'spreads' the whole array, thus returning the final element only per entity. Here's the code at index.js:
import dataOfCars from "./data.js";
import { normalize, schema } from "normalizr";
const ownerSchema = new schema.Entity("owners");
const mechanicSchema = new schema.Entity("mechanics", {
mechanic: ownerSchema
});
const carSchema = new schema.Entity("cars", {
owner: ownerSchema,
mechanics: [mechanicSchema]
});
/* This method somehow returns the very final element */
const objectPost = Object.assign({}, ...dataOfCars);
const normalizedPost = normalize(objectPost, carSchema);
// The normalized object returning the 2/3 expected entities
console.log(normalizedPost);
I'm still relatively new to ES6 and I would love to know how this works out in the end! Thanks for the help in advance!
I have a structure like below;
var devices = {
'device-1' : {
'id' :'device1',
'template' :'template-1',
'user-1' :{
'name' : 'John Doe',
'authority' : 'author1',
},
'admin-1' :{
'name' : 'Bob Doe',
'authority' : 'author2',
},
'user-35' :{
'name' : 'Bill Doe',
'authority' : 'author1',
},
'author-42' :{
'name' : 'Jack Doe',
'authority' : 'author1|author3',
}
},
'device-2' : {
'id' :'device2',
'template' :'template-2',
'some-27' :{
'name' : 'John Doe',
'authority' : 'author1',
},
'other-42' :{
'name' : 'Jack Doe',
'authority' : 'author2',
}
},
'device-7' : {
'id' :'device7',
'template' :'template-1',
'user-2' :{
'name' : 'Samantha Doe',
'authority' : 'author2',
}
'admin-40' :{
'name' : 'Marry Doe',
'authority' : 'author1',
},
}
};
and I would like to get all 'value' entries of user-x elements by filtering their 'property' values.
Eg.
I would like filter all 'name's of users (no matter in which device and what are those user-ids) based on their 'authority' property and get 'John Doe','Bill Doe','Jack Doe','Marry Doe' (as an array) if I would like filter for 'author1' 'authority' so I can get which users have 'author1' authorities on any devices.
I've checked many places (including StackOverflow) but most of the examples are limited to two-dimensional object arrays, variables were specific or objects were based on an integer (like [0] => Array).
But in this example, 'device-x' and 'user-x' entries are uncertain (so I cannot say their values are these) but 'name' and 'authority' keys are certain (assign by the system) and the count of these variables can be varied (crud operations).
Thanks right now.
UPDATE : Because of my assumption error (I thought that if I write user-x parts different that each other, people think that these values are not follow any rule) question was not clear. So I edited in code.
Finally : owners of 'name' and 'authority' key-value pairs are user names and they are user defined.
So, all device objects will have id, template, unknown-user-field, but all unknown-user-fields must have 'name' and 'authority' key-value pairs.
Using reduce & filter & map.
Updated: I've added a isLikeUserObj function that probs for name & authority fields.
const devices = {
'device-1': {
'id': 'device1',
'template': 'template-1',
'user-1': {
'name': 'John Doe',
'authority': 'author1',
},
'admin-1': {
'name': 'Bob Doe',
'authority': 'author2',
},
'user-35': {
'name': 'Bill Doe',
'authority': 'author1',
},
'author-42': {
'name': 'Jack Doe',
'authority': 'author1|author3',
}
},
'device-2': {
'id': 'device2',
'template': 'template-2',
'some-27': {
'name': 'John Doe',
'authority': 'author1',
},
'other-42': {
'name': 'Jack Doe',
'authority': 'author2',
}
},
'device-7': {
'id': 'device7',
'template': 'template-1',
'user-2': {
'name': 'Samantha Doe',
'authority': 'author2',
},
'admin-40': {
'name': 'Marry Doe',
'authority': 'author1',
},
}
};
const result = getUserByAuthority('author3');
function getUserByAuthority(requiredAuth) {
return Object.keys(devices).reduce((result, deviceKey) => {
const users = Object.keys(devices[deviceKey])
.filter((key) => isUserLikeObj(devices[deviceKey][key]))
.map(userKey => devices[deviceKey][userKey])
.filter((user) => user.authority.split('|').indexOf(requiredAuth) > -1)
.map((user) => user.name)
return result.concat(users);
}, [])
}
function isUserLikeObj(value) {
return typeof value === 'object' && value.hasOwnProperty('name') && value.hasOwnProperty('authority')
}
console.log(result)
You can use for-in loop to traverse an object. Following ways could achieve your need
const result = []
for (let i in devices) {
for (let j in devices[i]) {
if (/user-\d+/.test(j)) {
if (devices[i][j].authority.split('|').indexOf('author1') !== -1) {
result.push(devices[i][j].name)
}
}
}
}
console.log(result)