Retrieve Index When Passing Object to Function - javascript

I'm passing an Object from an array of objects to a function. Is it possible to still retrieve the index number somehow from the object in the function?
I'm doing this in javaScript specifically within the controller of AngularJS.
For instance
var array= [
{
name: "name1"
},
{
name: "name2"
}
];
function( passedInObjectFromArray ) {
return passedInObjectFromArray.indexVal;
}

Yes you can do,
$scope.retrieveIndex = function(passedInObjectFromArray){
return array.indexOf(passedInObjectFromArray);
}

Related

find property inside nested array javascript

I have an object that contains data to display information pulled from the Notion API. I can see the data but not sure how I can extract nested array inside the current array. My goal is to use the category property to create a filter but first I need to get the string to create the condition.
Here is what the data looks like currently. How would I go about to filter out name: "commissions":
resultsArray:
0:
properties
category:
id: "sdasd"
multi_select:
0:
id:"324234"
name: "commissions"
I have tried use find but it doesn't do what I expect. My suspicion is that I will have to loop over the nested array again.
You can use find inside find condition
like this :
data.resultsArray.find(item=>item.category.multi_select.find(select=> select.name === "commissions"))
const data = {
resultsArray: [
{
category: {
id: 'sdasd',
multi_select: [
{
id: '324234',
name: 'commissions',
},
],
},
},
],
};
const result = data.resultsArray.find(item=>item.category.multi_select.find(select=> select.name === "commissions"))
console.log(result)

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

How to return new array with dynamically populated properties?

So my call returns something like:
data:
{
nameData: 'Test33333',
emailData: email#email.com,
urlLink: link.com
additionalDetails: [
{
field: 'email',
value: 'other#email.com'
},
{
field: 'name',
value: 'name1223'
}
]
}
Now, I want to make a function that would take the passed parameter (data) and make an array of objects, that should look like below. It should be done in more generic way.
Array output expectation:
fullData = [
{
name: 'data_name'
value: 'Test33333'
},
{
name: 'data_email',
value: 'email#email.com'
},
{
name: 'data_url',
value: 'Link.com'
},
extraData: [
//we never know which one will it return
]
];
It should be done in the function, with name, for example:
generateDataFromObj(data)
so
generateDataArrFromObj = (data) => {
//logic here that will map correctly the data
}
How can this be achieved? I am not really proficient with JavaScript, thanks.
Assuming that you keep your data property keys in camelCase this will work for any data you add, not just the data in the example. Here I've used planetLink. It reduces over the object keys using an initial empty array), extracts the new key name from the existing property key, and concatenates each new object to the returned array.
const data = { nameData: 'Test33333', emailData: 'email#email.com', planetLink: 'Mars' };
function generateDataArrFromObj(data) {
const regex = /([a-z]+)[A-Z]/;
// `reduce` over the object keys
return Object.keys(data).reduce((acc, c) => {
// match against the lowercase part of the key value
// and create the new key name `data_x`
const key = `data_${c.match(regex)[1]}`;
return acc.concat({ name: key, value: data[c] });
}, []);
}
console.log(generateDataArrFromObj(data));
Just run a map over the object keys, this will return an array populated by each item, then in the func map runs over each item, build an object like so:
Object.keys(myObj).map(key => {return {name: key, value: myObj[key]}})

psuhing an object inside another object

I want to create an object of objects which should be something like this.
let data={
{ _id:10010,
value:"tom"
},
{
_id:2002,
value:22882
}
}
One solution that i could think of was this .
let data = {};
data.content = ({
_id: 1001,
value: "tom"
});
data.content = ({
id: 10001,
status: "harry"
});
console.log(data);
However if we do this we can only have one content inside our main object .Can we accomplish the desired data format while creating an object of objects ?
You can use array.
let data=[
{ _id:10010,
value:"tom"
},
{ _id:2002,
value:22882
}
]
data.push({
_id:1001,
value:"tom"
});
data.push({
_id:1001,
value:"tom"
});
Push method will add object to the array. If you need something else you can create more complex function/class that handles the requirements, but this maybe would be enough.
I assume you need to do with array
let data=[];
data.push({
_id:1001,
value:"tom"
});
data.push({
id:10001,
status:"harry"
});
console.log(data);
You cannot create an "object of objects". Objects store data in key:value pairs. You might consider creating an array of objects, after which you can reference the array items using indexes:
let data = [];
data.push({
_id: 10010,
value: "tom"
});
data.push({
_id: 2002,
value: 22882
});
console.log(data);
You can make use of arrays in order to achieve the result.
let data = [];
data[0]= {
_id:10010,
value:"tom"
}
data[1]= {
_id:2002,
value:22882
}
and so on...
I believe what you really mean is
let data={
10010: { _id:10010,
value:"tom"
},
2002: {
_id:2002,
value:22882
}
}
Property of objects has to be key value pair, meaning in order to have a object nested in an object, as a value, u need to pair it with a key. Hence using the id of object as the key to store it.
data['10010'] = { _id: 10010, value: 'tom' };
data['2002'] = { _id: 2002, value: 22882 };

Categories