how to get object length in pure javascript? [duplicate] - javascript

This question already has answers here:
How to efficiently count the number of keys/properties of an object in JavaScript
(19 answers)
Closed 11 months ago.
how to get object length in pure javascript in this code
let myFavGames = {
"Trinity Universe": {
publisher: "NIS America",
price: 40,
},
"Titan Quest": {
publisher: "THQ",
bestThree: {
one: "Immortal Throne",
two: "Ragnarök",
three: "Atlantis",
},
price: 50,
},
YS: {
publisher: "Falcom",
bestThree: {
one: "Oath in Felghana",
two: "Ark Of Napishtim",
three: "origin",
},
price: 40,
},
};
// Code One => How To Get Object Length ?
let objectLength = ?;

You can use Object.keys() to get the number of keys in your object:
const myFavGames = {
"Trinity Universe": {
publisher: "NIS America",
price: 40,
},
"Titan Quest": {
publisher: "THQ",
bestThree: {
one: "Immortal Throne",
two: "Ragnarök",
three: "Atlantis",
},
price: 50,
},
YS: {
publisher: "Falcom",
bestThree: {
one: "Oath in Felghana",
two: "Ark Of Napishtim",
three: "origin",
},
price: 40,
},
};
const objectLength = Object.keys(myFavGames).length;
console.log(objectLength); // 3

The Object.keys() method returns an array of a given object's own enumerable property names.
console.log(Object.keys(myFavGames).length);

Related

How do I incorporate the index of an array while defining a property of said array within a class in JavaScript?

Sorry if the title makes no sense.. let me explain
Say I have the following 2d array.. the first array representing ice cream and the second representing milkshakes
menu = [ ['vanilla', 'chocolate', 'almond'],
['vanilla', 'pineapple', 'strawberry'] ]
Now I create a class that takes this array as input
class cafe{
constructor(menu){
this.iceCreams = menu[0]
this.milkshakes = menu[1]
}
}
Now I want to define a property called 'price' for each flavor of milkshake.
this.milkshakes[n].price = < a function that computes price based on value of n >
so that i can access them like this :
cafe.milkshakes[0].price
So how do I incorporate the index 'n' of the array while defining the property
I haven't tried anything bcos I dont know how to even approach this ☹️
You can do it in your constructor.
You can grab the names, and call map function on it and do whatever you want. Please check the following example. There, calculatePrice is a function that takes the index and returns the price based on the index.
class Cafe {
constructor (menu) {
this.iceCreams = menu[0].map((flavor, index) => {
return {
flavor,
price: calculatePrice(index)
}
});
this.milkshakes = menu[1].map((flavor, index) => {
return {
flavor,
price: calculatePrice(index)
}
});
}
This is a minimal answer.
UPDATE:
For a detailed and improved answer: https://codesandbox.io/s/cafe-example-wxp2c4
So, in the milkshakes array you need each item as an object data structure, not a string.
menu = [ ['vanilla', 'chocolate', 'almond'],
[{ flavor: 'vanilla' }, { flavor: 'pineapple' }, { flavor: 'strawberry' }] ]
and then you can loop through and set the price, something like this.
menu.milkshakes.forEach((item, index) => item.price = index))
you can use objects:
menu = [
[
{
name: "vanilla",
price: 200,
},
{
name: "chocolate",
price: 200,
},
{
name: "almond",
price: 200,
},
],
[
{
name: "vanilla",
price: 200,
},
{
name: "pineapple",
price: 200,
},
{
name: "strawberry",
price: 200,
},
],
];
and then:
class cafe{
constructor(menu){
this.iceCreams = menu[0]
this.milkshakes = menu[1]
}
}
now iceCreams and milshakes have the property price and name
example:
iceCreams[n].price
iceCreams[n].name

Get a property of a javascript object using another property [duplicate]

This question already has answers here:
How to find object in array by property in javascript?
(3 answers)
Closed 4 months ago.
Here's a list of objects for example:
const products = [
{
name: "Cherry",
price: 10,
quantity: 0,
productId: 1,
image: "../images/cherry.jpg"
},
{
name: "Orange",
price: 15,
quantity: 0,
productId: 2,
image: "../images/orange.jpg"
},
{
name: "Strawberry",
price: 3,
quantity: 0,
productId: 3,
image: "../images/strawberry.jpg"
}
];
I want to get the other properties of an object from the list using its productId. I'm a beginner in JavaScript so I can't seem to figure this out. Any help would be highly appreciated!
products.find((product) => product.productId === pid) // where pid is the id of the product you want to find
What i understand from your description is that you want to find out the product property of a specific items from the list for that you can use
==ES6==
products.filter( (item) => { return item.productId==productId})
==Vanila js==
products.filter(function(item) { return item.productId==productId})

js: How to filter object keys from an array of objects? [duplicate]

This question already has answers here:
Remove property for all objects in array
(18 answers)
Closed 7 months ago.
I have an array similar to this one
let array = [
{
name: "1-name",
age: 18,
direction: "jsjs"
phone: 7182718
},
{
name: "2-name",
age: 38,
direction: "jsjsjs"
},
{
name: "3-name",
age: 58,
direction: "jsjsjsjs"
}
]
and i want to filter it based on its keys to get an array like this
[
{
name: "1-name",
direction: "jsjs"
},
{
name: "2-name",
direction: "jsjsjs"
},
{
name: "3-name",
direction: "jsjsjsjs"
}
]
Can you please help me i've try to solve it with no success
You can you the array map function.
See an example here:
const arr = [
{
name: "1-name",
age: 18,
direction: "jsjs",
phone: 7182718
},
{
name: "2-name",
age: 38,
direction: "jsjsjs",
phone: 7182718
},
{
name: "3-name",
age: 58,
direction: "jsjsjsjs",
phone: 7182718
}
]
const result = arr.map(({ name, direction }) => {
return {
name,
direction
};
})
console.log(result);
You Can Try This Code:
let newArr = [];
array.forEach((e) => {
newArr.push({ name: e.name, direction: e.direction });
});
The map method will work. How you implement this depends on whether you want to create a new array result with the previous objects deleted, or simply return the ones you want to keep. This will create a new array your original array will remain unaffected.
array.map(function (result) {
delete result.age;
delete result.phone;
});
console.log(result)

Finding the name of an object [duplicate]

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

How to override the nested array object

I would like to know how to overwrite the values in an object array if exists else merge the objects using Javascript.
For example, targetAmount matches in parent, so I need to override the matched value and remaining values just insert the parent object.
var my_obj = [{
description: "transferwise_description"
fee: "0.5"
id: "transferwise"
logo: "transferwiselogo.png"
name: "Transferwise"
speed: "1 Days"
targetAmount: "2000"
}]
var tomerge_obj = {
rate: 51.00674
source: "SGD"
sourceAmount: 1000
target: "INR"
targetAmount: 50688.97
type: "REGULAR"
}
Expected Output
var merged_object = [{
description: "transferwise_description"
fee: "0.5"
id: "transferwise"
logo: "transferwiselogo.png"
name: "Transferwise"
speed: "1 Days"
rate: 51.00674
source: "SGD"
sourceAmount: 1000
target: "INR"
targetAmount: 50688.97
type: "REGULAR"
}]
You can do it in one line with Object.assign(). You can find more documentation on it here.
const result = Object.assign({}, my_obj[0], tomerge_obj);
You can simply use destructuring, this way:
var merged_object = {...my_obj[0], ...tomerge_obj}
It will return a new object with the values from tomerge_obj duplicated keys will replace the ones in the object inside my_obj.
You can also use Object.assign and assign both objects to an empty one to achieve the same result.
var my_obj = [{
description: "transferwise_description",
fee: "0.5",
id: "transferwise",
logo: "transferwiselogo.png",
name: "Transferwise",
speed: "1 Days",
targetAmount: "2000"
}];
var tomerge_obj = {
rate: 51.00674,
source: "SGD",
sourceAmount: 1000,
target: "INR",
targetAmount: 50688.97,
type: "REGULAR"
};
my_obj[0] = {...my_obj[0], ...tomerge_obj};
console.log(my_obj);
my_obj[0] = {...my_obj[0], ...tomerge_obj};
'...' is the spread operator and is commonly used for object de-structuring.
What this will essentially do is that it will reassign the first element of the array with the newly created object by spreading the attributes of the two objects.
The console.log will prove the assertion.
jQuery's extend is here just for that (answered this because you tagged jQuery, it has a much wider browser support than assign or spread operator)
Note that it modifies the original object, if you don't want, use var res = $.extend(true, {}, my_obj[0], tomerge_obj);
var my_obj= [
{
description: "transferwise_description",
fee: "0.5",
id: "transferwise",
logo: "transferwiselogo.png",
name: "Transferwise",
speed: "1 Days",
targetAmount: "2000",
}
];
var tomerge_obj = {
rate: 51.00674,
source: "SGD",
sourceAmount: 1000,
target: "INR",
targetAmount: 50688.97,
type: "REGULAR",
};
$.extend(true, my_obj[0], tomerge_obj)
console.log(my_obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Categories

Resources