Accessing Object inside Array - javascript

I'm trying to access values inside Firebase array > object.
When I try to access values inside v-for, it works well. But I cannot do this: postDetail.author. It returns undefined. What's the solution?

Since postDetail is an array of object to access properties inside its objects, you need do something like postDetail[Index].prop
var postDetail =[{"author" : "abc", "meta" : "xyz"}];
console.log(postDetail[0].author);

If you want get only author try it:
var postDetails = [{
author: "John",
category: "Tech"
}];
var inner = postDetails.map(function(e) {
return e.autor;
});
console.log(inner);

// Array of object
var persons = [
{
name: "shubham",
age: 22,
comments: ["Good", "Awesome"]
},
{
name: "Ankit",
age: 24,
comments: ["Fine", "Decent"]
},
{
name: "Arvind",
age: 26,
comments: ["Awesome", "Handsome"]
},
{
name: "Ashwani",
age: 28,
comments: ["Very Good", "Lovely"]
}
];
var data = persons.map(person => {
console.log(person.name);
console.log(person.age);
person.comments.map((comment, index) => console.log(index + " " + comment));
});

Related

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)

Javascript grouping by data from data and returning array of objects

I have 100 objects of data within an array that looks like this:
{
id: "1",
date: "2022/01/01",
name: "John",
},
{
id: "2",
date: "2022/01/02",
name: "Chris",
},
I am trying to return an array of objects by date that also returns the names.
For example:
[
{
date: "2022/01/01",
names: ["John", "Steve"...]
},
{
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
]
I have tried using the reduce method:
const groupedByDate = () =>
data.reduce((itemsIterated, { date, name }) => {
if (!itemsIterated[date]) {
itemsIterated[date] = {
date,
names: [],
};
}
itemsIterated[date].names.push(name);
return itemsIterated;
}, []);
The issue is this gives me array with a key of the date and then the object with date/names but I don't know how to return just the array of objects by date.
The function groupedByDate would return an object like this -
const result = {
'2022/01/01': {
date: "2022/01/01",
names: ["John", "Steve"...]
},
'2022/01/02': {
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
}
However, to retrieve it in the format you need, you would need to make use of Object.values().
Object.values(result);
/*
[
{
date: "2022/01/01",
names: ["John", "Steve"...]
},
{
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
]
*/
NOTE
To learn more about Object.values() - MDN
reduce's second parameter is the initial value of the accumulator. Here, we would need to use {} instead of [] in the groupedByDate function.

How to relate two (or more) objects through a property (in javascript)?

Let's say I have these two objects:
let person1 = {name: "Charlie", age: 65, childrenNames:["Ruth", "Charlie Jr."] parentNames: ["Dolph", "Grace"]};
let person2 = {name: "Charlie Jr.", age: 34, childrenNames:[] parentNames: ["Charlie", "Grace"]};
Now let's say I want to express the fact that person1 is person2's father and, consequently, that person2 is person1's son. That is, the "Charlie Jr" in the person1's childrenNames property is person2 and the "Charlie" in the person2's parentNames property is person1.
How could I achieve this? I don't see how embedding one object inside the other would solve the problem, but simply replicate it. Is there a way to make a property inside an object a sort of identifier for another object?
Thanks so much!
For example if you want to know if someone is the child of person 1, you can do something like this:
person1.childrenNames.forEach((childrenName) => {
if(childrenName=== person2.name) {
console.log(person1.name + ' is the parent of + person2.name);
});
Also you can do a nested function so you can check if the person if the parent of multiple persons.
Why not add relationship indexes ? combine your people, to 1 people array.
Iterate and add instead of parentNames, parentIndexes. This way, instead of looking for parents or sons by names, you have the index.
Note, to make my example simple, I am only doing parent to son relationship. You can easily add a son to parent relationship using the exact same logic.
Example
if (peopleArray[i].parentsIndex.length > 0) {
// get first parent
//peopleArray[peopleArray[i].parentsIndex[0]];
}
Modify your object.
let peopleArray = [
{
name: "Charlie",
age: 65,
parentNames: ["Dolph", "Grace"]
},
{
name: "Grace",
age: 65,
parentNames: ["Dolph", "Grace"]
},
{
name: "Dolph",
age: 65,
parentNames: ["ADSGS", "Grace"]
}
];
peopleArray = peopleArray.map(callback.bind(null));
function callback(item) {
item["parentsIndex"] = [];
for (let i = 0; i < item.parentNames.length; i++) {
let parentObj = peopleArray.find(x => x.name === item.parentNames[i]);
if (parentObj !== undefined) {
item["parentsIndex"].push(peopleArray.indexOf(parentObj));
}
}
return item;
}
console.log(peopleArray);
// use case
if (peopleArray[0].parentsIndex.length > 0) {
// get first parent
//peopleArray[peopleArray[0].parentsIndex[0]];
}
I guess it depends on how complicated your scenario would be and what you would like to achieve, but say you add an extra table for relations. This table could hold information on the type of relation 2 persons share, and could then be used to look up that data.
For example, if we have 4 persons, from which 2 are parents (Charlie & Grace) and 1 is the son (Charlie Jr), we could form a relation table as below.
We don't need to indicate that Charlie Jr is a son, as he we already know the parents of the child.
const familyDb = {
persons: [
{ id: 1, name: 'Charlie', age: 68 },
{ id: 2, name: 'Grace', age: 64 },
{ id: 3, name: 'Charlie Jr', age: 34 },
{ id: 4, name: 'Grace', age: 36 }
],
relations: [
{ id: 1, person1: 1, person2: 2, type: 'spouse', from: 1970, till: null },
{ id: 2, person1: 3, person2: 4, type: 'spouse', from: 2010, till: null },
{ id: 3, person1: 1, person2: 3, type: 'parent' },
{ id: 3, person1: 2, person2: 3, type: 'parent' }
]
};
function getParents( person ) {
return familyDb.relations.filter( relation => relation.person2 === person.id && relation.type === 'parent' );
}
function getChildren( person ) {
return familyDb.relations.filter( relation => relation.person1 === person.id && relation.type === 'parent' );
}
console.log( getParents( familyDb.persons[2] ) );
console.log( getChildren( familyDb.persons[0] ) );
So the above code kinda takes a rudimentary approach to this, you have:
a unique id identifying a person (name matching would be hard in your example as Grace is both the mom of Charlie & Charlie Jr)
a table identifying a relation of some type between two persons
After that you just need a way to look up the information from your dataset and you have a way to get started

Ramda JS: How to perform a map where I call R.replace for a given property on each object?

Given the following data:
const my_data = [
{
name: "John",
age: 22
},
{
name: "Johnny",
age: 15
},
{
name: "Dave",
age: 27
}
]
I want to transform the data such that the substring "John" is replaced with "Ben" in each of the name properties so it looks like this:
[
{
name: "Ben",
age: 22
},
{
name: "Benny",
age: 15
},
{
name: "Dave",
age: 27
}
]
I want to do so in the proper functional way (I think is points-free but I am still learning), so I can reuse this in a pipeline, say first reducing by age and then doing the replace, or doing the replace first then doing a sort. How would I do this using the Ramda functions?
var fix_names = ???
var fixed_data = R.map( fix_names, my_data );
R.map(R.over(R.lensProp('name'), R.replace('John', 'Ben')))(my_data)
See R.over and R.lensProp.
There's no reason to prefer point-free functions. Readability is what really matters:
var myData = [ new Person("John", 22)
, new Person("Johnny", 15)
, new Person("Dave", 27)
];
var fixedData = myData.map(fixName);
alert(JSON.stringify(fixedData, null, 4));
function fixName(person) {
return Object.assign(new Person, person, {
name: person.name.replace(/John/g, "Ben")
});
}
function Person(name, age) {
this.name = name;
this.age = age;
}
Point-free functions are useful in very limited cases like eta conversion and function composition. Point-free functions should not be treated as the cornerstone of functional programming.

Is there any key/value pair structure in JavaScript?

I want to store information like:
Pseudo-Code
array(manager) = {"Prateek","Rudresh","Prashant"};
array(employee) = {"namit","amit","sushil"};
array(hr) = {"priya","seema","nakul"};
What kind of data structure can I use?
You can use arrays to store list of data ; and objects for key-value
In you case, you'd probably use both :
var data = {
'manager': ["Prateek","Rudresh","Prashant"],
'employee': ["namit","amit","sushil"],
'hr': ["priya","seema","nakul"]
};
Here, data is an object ; which contains three arrays.
An object:
var myobj = {
"manager": ["Prateek","Rudresh","Prashant"],
"employee": ["namit","amit","sushil"],
"hr": ["priya","seema","nakul"]
}
alert(myobj['employee'][1]); // Outputs "amit"
A normal object will do:
var a = {
key1: "value1",
key2: ["value2.1","value2.2"]
/*etc*/
}
Access with:
a.key1
a["key1"]
With ES2015/ES6 you have Map type.
Using Map your code will look like
const map = new Map([
['manager', ['Prateek', 'Rudresh', 'Prashant']],
['employee', ['namit', 'amit', 'sushil']],
['hr', ['priya', 'seema', 'nakul']]
])
console.log(...map.entries())
To get Individual value you can use Map.get('key') method
you could store them in an array of objects:
var Staff = [
{ name: 'Prateek', role: manager },
{ name: 'Rudresh', role: manager },
{ name: 'Prashant', role: manager },
{ name: 'Namit', role: employee },
{ name: 'Amit', role: employee },
{ name: 'Sushil', role: employee },
{ name: 'Priya', role: hr },
{ name: 'Seema', role: hr },
{ name: 'Nakul', role: hr },
];
adding an ID attribute might be useful too depending on your application. i.e
{ id: 223, name: 'Prateek', role: manager },
Or use JSON like this. A little change of your pseudo code, but it will be serchable and extendable.
var Person = [
{
"name": "Prateek",
"position": "manager"},
{
"name": "James",
"position": "employee"}
];
Yes there is:
var theArray = {};
theArray["manager"] = ["Prateek","Rudresh","Prashant"];
theArray["employee"] = ["namit","amit","sushil"];
theArray["hr"] = ["priya","seema","nakul"];
Even you can use stuff as below :-
var obj = new Object();
obj.name = 'Jatin';
obj.place = 'Delhi';

Categories

Resources