Finding the name of an object [duplicate] - javascript

This question already has answers here:
How do you print the names of variables inside of an array?
(4 answers)
Closed 12 months ago.
Let's say I have some Javascript with the following:
Foo = {
alpha: { Name: "Alpha", Description: "Ipso Lorem" },
bravo: { Name: "Bravo", Description: "Nanu, Nanu" },
delta: { Name: "Fly with me", Description: "Klaatu barata nikto" }
};
Table = [ Foo.alpha, Foo.bravo, Foo.delta];
x = Table[1];
Is there any way of looking at x and getting the identifier bravo? I'm fully aware that I can use x.Name or x.Description, but let's say that I need to know the name for something elsewhere. In one task I experimented with, I was forced to add a redundant id : "bravo" to each entry, but that was a pain.
My gut tells me it can't be done. But I'm hoping someone else can tell me otherwise.

Foo = {
alpha: { Name: "Alpha", Description: "Ipso Lorem" },
bravo: { Name: "Bravo", Description: "Nanu, Nanu" },
delta: { Name: "Fly with me", Description: "Klaatu barata nikto" }
};
Table = [ ];
for(let val in Foo){
let obj = Foo[val];
obj = {...obj , id:val }
Table.push(obj)
}
x = Table[1];
console.log(x)

Personally, I'd use a Proxy ...
const _Foo = {
alpha: { Name: "Alpha", Description: "Ipso Lorem" },
bravo: { Name: "Bravo", Description: "Nanu, Nanu" },
delta: { Name: "Fly with me", Description: "Klaatu barata nikto" }
};
const Foo = new Proxy(_Foo, {
get(target, id) {
if (target.hasOwnProperty(id)) {
return {...target[id], id};
}
return target[id];
}
});
const Table = [ Foo.alpha, Foo.bravo, Foo.delta ];
console.log(Table[0])

Related

How to limit an array field in javascript object to a certain length

I know this may a simple problem but I have a the following javascript object:
const categories = {
title: 'cat1',
contents: [
{
name: 'cont1'
},
{
name: 'cont2'
},
{
name: 'cont3'
}
]
}
How can a transform this categories object so it has only 2 contents element as an example?
const transformedCategories = {
title: 'cat1',
contents: [
{
name: 'cont1'
},
{
name: 'cont2'
}
]
}
A couple of ways to do it:
const transformedCategories = {
title: categories.title,
contents: categories.contents.slice(0,2) // you can also use splice here
}
Another, slightly cheeky way:
const contents = [...categories.contents];
contents.length = 2;
const transformedCategories = {...categories, contents}

How do you check if value exist in object of object's array?

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

Dynamically parsing JSON arrays in JavaScript

I'm trying to parse a JSON file stored locally on my machine in JavaScript in discord.js (v12). This JSON has several keys and values:
{
"name": "Robert",
"rank": "Owner",
"hobbies": [{
"id": 1,
"name": "gaming"
}, {
"id": 2,
"name": "listening to music"
}, {
"id": 3,
"name": "vibing"
}, {
"id": 4,
"name": "driving down the highway"
}],
"roles": [{
"id": 1,
"name": "Founder"
}, {
"id": 2,
"name": "Premium Member"
}]
}
I want to send the above in a message on Discord as follows:
name: Robert
rank: Owner
hobbies: gaming, listening to music, vibing, driving down the highway
roles: Founder, Premium Member
I also want this to be dynamic. Meaning my code should adapt if a new key and value is added to the current set.
With the current code used, this is my result:
name: Robert
rank: Owner
hobbies: gaming, listening to music, vibing, driving down the highway
This is my current code:
let noted = ``
var raw = fs.readFileSync(name)
var obj = JSON.parse(raw)
for (var item in obj) {
if (obj[item] instanceof Object) {
for (var i in obj.hobbies) {
noted += `${obj.hobbies[i].name}, `
}
} else {
noted += `${item}: ${obj[item]}\n`
noted += `hobbies: `
}
}
message.channel.send(noted)
The variable name is const name = require("./names.json"); at the top of the code.
This code works fine with name, rank and hobbies.
roles has to be manually checked in the for loop if I want it to be visible. My goal is to cause any new keys to be added to be automatically detected and added into the noted variable.
I've seen something similar done using map(), but I tried it without getting anywhere good. This is rather sloppy code as well but I'm not interested in keeping it clean.
You could do something like this with map and join:
const obj = {"name":"Robert","rank":"Owner","hobbies":[{"id":1,"name":"gaming"},{"id":2,"name":"listening to music"},{"id":3,"name":"vibing"},{"id":4,"name":"driving down the highway"}],"roles":[{"id":1,"name":"Founder"},{"id":2,"name":"Premium Member"}]};
const noted = Object.entries(obj)
.map(([key, val]) =>
`${key}: ${
val instanceof Array ? val.map(x => x.name).join(', ') : val
}`)
.join('\n');
console.log(noted);
Here is an iterative solution using object-scan.
I find it a bit easier to read, but most importantly it is very flexible as to which keys you want to traverse.
// const objectScan = require('object-scan');
const myData = { name: 'Robert', rank: 'Owner', hobbies: [{ id: 1, name: 'gaming' }, { id: 2, name: 'listening to music' }, { id: 3, name: 'vibing' }, { id: 4, name: 'driving down the highway' }], roles: [{ id: 1, name: 'Founder' }, { id: 2, name: 'Premium Member' }] };
const convert = (data) => {
const r = objectScan(['*', '*[*].name'], {
reverse: false,
filterFn: ({ isLeaf, context, key, value }) => {
if (isLeaf) {
if (!(key[0] in context)) {
context[key[0]] = value;
} else {
context[key[0]] += `, ${value}`;
}
}
}
})(data, {});
return Object.entries(r).map(([k, v]) => `${k}: ${v}`).join('\n');
};
console.log(convert(myData));
/* =>
name: Robert
rank: Owner
hobbies: gaming, listening to music, vibing, driving down the highway
roles: Founder, Premium Member
*/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan

Omitting one or multiple values in javascript using lodash

I have a complex structure and I want to omit some properties from this structure for final value
let ListofWorlds = {
listOfCountries: [{
add: [{
id: 1,
updated: {
areacode: 123,
city: {
city: {'Austrailia'},
houses: {1000}
}
}
}], remove: []
}]
}
I want to omit city property from this structure and need this
let ListofWorlds = {
listOfCountries: [{
add: [{
id: 1,
updated: {
areacode: 123
}
}], remove: []
}]
}
This is what I have tried
let newListOfWorls = _.map(ListofWorlds, function (worlds) {
return _.omit(worlds, ['city']); })
Appreciate the help and knowledge
This is what i have tried.
let ListofWorlds = {
listOfCountries: [{
add: [{
id: 1,
updated: {
areacode: 123,
city: {
city: 'Austrailia',
houses: 1000
}
}
}], remove: []
}]}
const newList = ListofWorlds.listOfCountries.map(arr=>{
arr.add.forEach((item,index)=>{
arr.add[index] = _.omit(item,'updated.city')
})
return arr
})
Probably not the best way to do it, but hey it works, and why your code doesn't work probably you mapped an Object ListofWorlds and you need to be specific which field you want to be omitted

Converting an array of objects into an object of objects

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!

Categories

Resources