How to display the Array length in console with JavaScript/AngularJS - javascript

I have a question about displaying the Array length in console.log().
Here is a simple example:
vm.list = CrudService.getAllData();
function getAllFonds() {
return ResService.names.query(
succResp,
errResp
);
}
function succResp(resp) {
return resp;
}
function ResService($resource, baseUrl) {
return {
names: $resource(baseUrl + '/api/list/:Id', {
Id: '#Id'
}, {
'update': {
method: 'PUT'
}
}),
....}
}
$log.info(vm.list);
When I'm opening the console, there will be display only:
Array [ ]
Only when I click on "Array" then I see on the right side that the array contains 47 objects.
Is there a possibility to display in console:
Array [47]
?
EDIT:
When I'm using:
$log.info(vm.list.length);
it returns 0.

I think you're looking for this:
console.log(vm.list.length);
or in your case
$log.info(vm.list.length);

Sure there is
console.log(yourArray.length);
Or if you insist on that format you can do
console.log('Array['+yourArray.length+']');
Take a peek at the docs

Related

Saving array and objects within said array

I am trying to make a simple to do app using vue.js, I want to try and save my to-dos that are set in the array so that when I reset the site, they still remain. Looking through some of the documentation I arrived at this:
data() {
return {
array: [
{id: 1, label: 'learn vuejs'},
]
}
},
methods: {
persist() {
localStorage.array = this.array;
alert('items saved')
}
},
mounted() {
if (localStorage.array && localStorage.array.id) {
this.array = localStorage.array;
this.array[id] = localStorage.array.id;
}
},
while this does save my array to localStorage, IT DOES NOT THE OBJECTS WITHIN. When I check localStorage in the console it shows :
array: "[object Object]"
anyone knows how to save the items within the array? if you do please explain it to me.
You need to store them as string. So localStorage.array = JSON.stringify(this.array), and when fetching from localStorage this.array = JSON.parse(localStorage.array);

Finding value in json array and replacing it using Typscript [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
I have a file with 1000s of json rows like below. Im having difficulties locating a specific key in the array.
example json:
{"connection":"98374"
,"db":"8",
,"timestamp":"159905411631"
,"event":"DataCatch"
,"data":[{"key":"ruleid","value":"111"}
,{"key":"responseid","value":"155-response-4"}
,{"key":"responsetype","value":"Capture"}
,{"key":"reason","value":"ClientVisit"}
,{"key":"subreason","value":""}
,{"key":"score","value":"0.00"}
,{"key":"comment","value":""}]
}
I need to be able to find the "reason" key in the "data" array and replace the "value" with "test". The "data" array doesn't always appear on every json row, only when the "event" "dataCatch" is present.
I can parse it into a variable but I can only call the "data" array as a whole. Any ideas how to target specific values in an array?
Having a little trouble with this in Typescript.
There are any number of ways to go about this, but here's one.
First, parse your JSON into an array of objects.
Each element of the array will then look something like this:
{
connection: '98374',
db: '8',
timestamp: '159905411631'
event: 'DataCatch',
data: [
{ key: 'ruleid', value: '111' },
{ key: 'responseid', value: '155-response-4' },
{ key: 'responsetype', value: 'Capture' },
{ key: 'reason', value: 'ClientVisit' },
{ key: 'subreason', value: '' },
{ key: 'score', value: '0.00' },
{ key: 'comment', value: '' },
],
}
Let's call our array of objects allData, so we can refer to it later.
Now we can begin our "surgery".
We'll work from the inside-out, first looking at what needs to be done to a specific entry in an element's data array.
Here's a function that will do just what we need:
function updateReason(entry) {
if (entry.key === 'reason') {
return { ...entry, value: 'test' };
} else {
return entry;
}
}
This function checks if the provided entry has a key with a value of 'reason', and -- if so -- returns a new entry that is identical to the provided one except its value is 'test'.
How can we use this to update an entire data array (in an entry that has data, that is)?
We simply delegate the work to our dear friend map:
function updateData(data) {
// or simply `data.map(updateEntry);`
return data.map(entry => updateEntry(entry));
}
We're slowly working our way "outwards".
What about updating an entire entry in our big allData array (which may or may not contain data)?
// I've called such an entry a "collection", because I already used the name
// "entry" above :(
// A "collection" is just an entry in the big `allData` array.
function updateCollection(collection) {
if (collection.event === 'DataCatch') {
return {
...collection, // Leave everything else the way it is
data: updateData(collection.data), // But update the `data` array
};
} else {
return collection;
}
}
So close.
The last thing we need to do is apply this transformation to every element of our parsed allData array:
// or `allData.map(updateCollection);`
const updatedData = allData.map(collection => updateCollection(collection));
Also:
Q: Wouldn't it be cheaper to mutate the entry?
A: It would be cheaper, but not that much cheaper, due to a large amount of "structural sharing" that occurs here. I would recommend this approach unless you either need to mutate your input for some reason, or performance requirements demand it.
You need to map over the data key in your data variable like this.
data.data = data.data.map((item) => {
if (item.key === "reason") {
item.value = "test";
}
return item;
});
the data key is an array of values, so you need to loop through it and compare the value of the key property to the value you are looking for, if it matches then you can update the value property
https://codesandbox.io/s/angry-shirley-1gh83?file=/src/index.ts:666-782

Turn Array with Key Values into JSON object in JavaScript

I have an array in JavaScript that I use JSON.stringify() on that ends up looking like this after:
[
{
"typeOfLoan":"Home"
},
{
"typeOfResidency":"Primary"
},
{
"downPayment":"5%"
},
{
"stage":"Just Looking"
},
{
"firstName":"Jared"
},
{
"lastName":"Example"
},
{
"email":"Jared#demo.com"
},
{
"cell":"8888888888"
},
{
"loanofficer":"Jim Loan"
}
]
I want the output to be a standard JSON object so that I can send it in a POST. Before this gets marked as duplicate, I have tried all of the answers I could possibly find already and they all end up not working or having syntax errors that I do not understand how to fix. This array is stored in variable jsonArray.
The array of objects, all with a single key, seems fishy. I suppose you want a single object literal with all the keys, which you can then send to you backend (and parse there). So first, reduce the many objects in a single one, then implement your ajax call to POST it to wherever. Here's how to reduce it:
let arr = [{"typeOfLoan":"Home"},{"typeOfResidency":"Primary"},{"downPayment":"5%"},{"stage":"Just Looking"},{"firstName":"Jared"},{"lastName":"Example"},{"email":"Jared#demo.com"},{"cell":"8888888888"},{"loanofficer":"Jim Loan"}];
let res = arr.reduce((a,b) => {
let key = Object.keys(b)[0];
a[key] = b[key];
return a;
}, {});
console.log(res);
Depending on what you use to send it to the backend, you might need to use JSON.stringify on res
Before stringifying, convert your request payload from an array to an object.
const arr = [{"typeOfLoan":"Home"},{"typeOfResidency":"Primary"},{"downPayment":"5%"},{"stage":"Just Looking"},{"firstName":"Jared"},{"lastName":"Example"},{"email":"Jared#demo.com"},{"cell":"8888888888"},{"loanofficer":"Jim Loan"}];
const payload = arr.reduce(function(acc, prev){
return Object.assign(acc, prev);
}, {});
console.log(payload);

Javascript loop through several objects and return true if

What is the best way of getting javascript/jquery to look through these two objects and return a 'true' if slug contains 'gift_wrap'. Please note Objects within CONTENT can vary.
If TRUE, then my code will do something :)
You could iterate over all keys and check if there is any wanted string. If found, break the loop and return true. If not found false is returned.
Best friends are:
Object.keys for getting all property names
Array#some for iterating and check.
function isGift() {
return Object.keys(cart.contents).some(function (k) {
return cart.contents[k].slug === 'gift-wrap';
});
}
var cart = { contents: { '8734918ab768671231': { sku: 'MOB101', slug: 'moby-dick-party-picks' }, '873124918ab7686711': { sku: 'gift', slug: 'gift-wrap' } } }
console.log(isGift());

Unshift from object list without using delete?

If I can access an object from an object using list[value][index], how can I delete or unshift that object from list without using delete? (since that isn't possible in an object list)
My object looks like this:
var list = {
'test1': [
{
example1: 'hello1'
},
{
example2: 'world1'
}
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
After deleting an object, I want it to look like this:
var list = {
'test1': [
{
example1: 'hello1'
}
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
When I use delete, it looks like this:
var list = {
'test1': [
{
example1: 'hello1'
},
null
]
'test2': [
{
example1: 'hello2'
},
{
example2: 'world2'
}
]
};
You can remove the object from list by setting the value of list[key] to undefined. This won't remove the key, however - you'd need delete to do that:
list['test1'] = undefined; // list is now { test1: undefined, test2: [ ... ]}
delete list['test1']; // list is now { test2: [ ... ] }
Is there a particular reason you don't want to use delete? It won't make a difference if you're just checking list['test1'] for truthiness (e.g. if (list['test1']) ...), but if you want to iterate through list using for (var key in list) or something like that, delete is a better option.
EDIT: Ok, it looks like your actual question is "How can I remove a value from an array?", since that's what you're doing - the fact that your array is within an object, or contains objects rather than other values, is irrelevant. To do this, use the splice() method:
list.test1.splice(1,1); // list.test1 has been modified in-place
(Rewritten for corrected question.)
You can write:
list[value].splice(index, 1);
to delete list[value][index] and thereby shorten the array by one. (The above "replaces" 1 element, starting at position index, with no elements; see splice in MDN for general documentation on the method.)
Here is an example using splice:
http://jsfiddle.net/hellslam/SeW3d/

Categories