This question already has answers here:
Searching for items in a JSON array Using Node (preferably without iteration)
(6 answers)
Closed 5 years ago.
I have the following function that receives a JSON array templates and returns a JSON object.
The code executes the console.log. However, it always returns the null at the end of the function. Any ideas?
function getTemplate(templates, myId) {
Object.keys(templates).some(obj => {
if (templates[obj].id === myId) {
console.log('HELLO');
return templates[obj];
}
});
return null;
}
template array
[
{
"id": 80,
"name": "template 1"
},
{
"id": 81,
"name": "template 2"
}
]
However, it always returns null.
Here is working example,
use .find instead of .some. We always expect to get one object.
function getTemplate(templates, myId) {
return templates.find(template => template.id === myId);
}
var array =
[
{
"id": 80,
"name": "template 1"
},
{
"id": 81,
"name": "template 2"
}
]
console.log(getTemplate(array, 80));
Related
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 1 year ago.
I currently have an array that has 2 levels. I am attempting to build two new arrays from the initial array but seem to be stuck with the method to use. I have attempted a forEach(), while loop, as well as push to no avail.
My current array structure:
[
{
"attributes": {
"Summary": 10,
"class": "Blue"
}
},
{
"attributes": {
"Summary": 63,
"class":"Red"
}
}
]
I am looking to build two arrays, namely one for summary values, and one for class values.
Are my approaches of a forEach or while loop on the correct path?
If you have an array and want to transform that into another array, the simplest way is to use map (which basically creates a new array containing the results of running each element through a function):
const arr = [
{
"attributes": {
"Summary": 10,
"class": "Blue"
}
},
{
"attributes": {
"Summary": 63,
"class":"Red"
}
}
];
const summaries = arr.map(e => e.attributes.Summary);
const classes = arr.map(e => e.attributes.class);
If you want to accomplish this using forEach, here's one way to do it:
const aryInitial = [
{
"attributes": {
"Summary": 10,
"class": "Blue"
}
},
{
"attributes": {
"Summary": 63,
"class":"Red"
}
}
];
let arySummary = [];
let aryClass = [];
aryInitial.forEach((obj)=>
{
arySummary.push(obj.attributes.Summary);
aryClass.push(obj.attributes.class);
});
console.log("Summary Array:",arySummary);
console.log("Class Array:",aryClass);
This question already has answers here:
Using bracket notation opposed to eval
(1 answer)
Convert a string to a variable name in javascript?
(3 answers)
Closed 1 year ago.
I have data like this
{
"data": {
"x": [
{
"id": 1,
"y": "yData1"
},
{
"id": 2,
"y": "yData2"
}
],
"xx": {
"xxx": [
{
"id": 1,
"yyy": "yyyData1"
},
{
"id": 2,
"yyy": "yyyData2"
}
]
}
}
}
sometime i just want object x or xx or xxx or many sub children in datas, i ready using eval for filter by using object name to return data
filter(data: any, key: any) {
return eval("data." + key)
}
any idea ?? because eval in typescript/javascript not recommended
Just use bracket notation in order to use variable values as key:
filter(data: any, key: any) {
return data[key];
}
This question already has answers here:
Remove property for all objects in array
(18 answers)
How to get a subset of a javascript object's properties
(36 answers)
How to map more than one property from an array of objects [duplicate]
(7 answers)
Closed 2 years ago.
I am trying to figure out if I can send only relevant javascript info to the frontend from the backend because I want to hide things like ID, and others when my frontend makes a request.
To put things in perspective, here is a dummy code.
[
{
"_id": "215874514845452155",
"greeting":"Hello there"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi"
},
]
when requesting, I want to get result like:
[
{
"greeting": "Hello there"
},
{
"greeting": "General Kenobi"
},
]
I am still learning stuff and I know about loop function but I want to know if there is some neat trick to it. I am coming from R programming, we hate loops.
Use Array.prototype.map:
const input = [
{
"_id": "215874514845452155",
"greeting":"Hello there",
"other":"foo"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi",
"other":"bar"
},
];
const result = input.map(({greeting,other}) => ({greeting,other}));
console.log(result);
The above is a shorthand way of writing this:
const input = [
{
"_id": "215874514845452155",
"greeting":"Hello there",
"other":"foo"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi",
"other":"bar"
},
];
const result = input.map(x => {
return {
greeting: x.greeting,
other: x.other
}
});
console.log(result);
This question already has answers here:
Check if object value exists within a Javascript array of objects and if not add a new object to array
(22 answers)
Closed 5 years ago.
I have an array of objects like
[
{
"name": "Name 1",
"id": "1245"
},
{
"name": "Name 2",
"id": "9788"
},
{
"name": "Name 3",
"id": "5694"
},
{
"name": "Name 4",
"id": "4523"
},
{
"name": "Name 5",
"id": "4567"
}
]
I need to check if the array contains an object with an ID (let's say "1111"). If ID not found in any of the objects inside array, then place the new object(e.g., {"name":"Test 0","id":"1111"}) at the beginning of the array.
PS: Is there methods other than array.unshift(newObj), to achieve the goal?
Edit: Okay. I did tried using array.indexOf(), but it seems like it only works with values not objects. I also try looping through the array, but didn't worked too. I cannot use ES6.
Without ES6 and assuming your object is named users you can conditionally add one if it doesn't exist like this:
function addUser(name, id) {
users.forEach(function(user) {
if (user.id === id) {
return user;
}
});
var newUser = {"name": name,"id": id}
users.unshift(newUser);
return newUser;
}
Using reduce
function hasId(array, id){
return array.reduce(function(sum, element){
return sum || element.id === id;
}, false);
}
if(hasId(array, 1111)){
array.splice(0, 0, newElement);
}
There are 1000 ways to do this. This solution works with es5, it isn't too efficient because it runs through the entire array. The fastest way is to do it in a for-loop, then return on the first found, but this looks prettier.
Using for loop
function hasId(array, id){
for(var i=0; i<array.length;i++){
if(array[i].id === id){
return true;
}
}
return false;
}
if(hasId(array, 1111)){
array.splice(0, 0, newElement);
}
This is the fastest method, it stops as soon as the first id is found
This question already has answers here:
How to efficiently count the number of keys/properties of an object in JavaScript
(19 answers)
Closed 6 years ago.
Is there any way to get the length from the following:
{
"11": {
"id": "456",
"uuid": "b596362a-b5bb-4n94-8fd5-1e9fh6fd877b",
"name": "Test",
"description": "Test"
},
"22": {
"id": "739",
"uuid": "c4ccbddf-5177-482f-b5e8-cdd4f699e6b7",
"name": "Test2",
"description": "Test2"
},
"33": {
"id": "737",
"uuid": "m4ccbddv-5177-482f-b5e8-cdd4f699e6b7",
"name": "Test3",
"description": "Test3"
}
}
The length should be 3. I tried to use JSON.stringify(data).length but this gives the length of the whole string.
In addition to above answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:
Object.keys(jsonArray).length;
You can use following function
function getJsonItemLength(item) {
if (typeof item !== undefined && varNotNull(item) && item) {
if (Array.isArray(item)) {
return item.length;
} else if (typeof item === 'object' ) {
return Object.keys(item).length;
} else if (typeof item === 'string' ) {
return item.length
} else {
return 0;
}
}
return 0;
}
using Object.keys you get the list of keys (in an array) so you could:
Object.keys(obj).length
If you're asking about the length of an associative-array-like object, that's your answer: Length of a JavaScript object
Or to save you the click:
Object.keys(myObj).length;