Destructuring nested objects in an array - javascript

I basically want to pull out the first object within an array and get it's name. The only challenge here is that I'm trying to destructure this within a parent object:
const exampleObject = {
collection: [{
name: "First Object",
}, {
name: "Second Object",
}],
};
const {
collection: [firstObject: {
name
}]
} = exampleObject;
console.log(firstObject);
Is sort of thing possible?

You need to switch it to:
{name: firstObject}
| |________ New variable name
|
|_________________ Property name
const exampleObject = {collection: [{name: "First Object",}, {name: "Second Object",}],}
const { collection: [{ name: firstObject }] } = exampleObject
console.log(firstObject)

If you need the name of first object you should write
const {
collection: [{ name }]
} = exampleObject;
console.log(name);

Related

Filtering array of objects against another array of objects?

customerProducts: [
{
name: "foo",
id: 123
},
{
name: "test",
id: 44
}
]
otherProducts: [
{
name: "other",
id: 44
},
{
name: "test",
id: 21
}
]
I want to iterate through customerProducts, which is an array of objects. I want to filter the customerProducts that have an ID that another array of objects, otherProducts, has. So for examople, I'd want the returned result in this case to be:
{
name: "test",
id: 44
}
since otherProducts has an id of 44.
I was thinking of mapping through otherProducts and just returning an array of IDs, then running a forEach on that but that seems like a long way of doing it.
Create an indexed Set of the values to filter by (id from otherProducts) then filter customerProducts by that Set
const customerProducts = [{name: "foo",id: 123},{name: "test",id: 44}]
const otherProducts = [{name: "other",id: 44},{name: "test",id: 21}]
const otherProductIds = new Set(otherProducts.map(({ id }) => id))
const filteredCustomerProducts = customerProducts.filter(({ id }) =>
otherProductIds.has(id))
console.info(filteredCustomerProducts)
This can be done by using array methods filter and some.
customerProducts.filter((x)=> otherProducts.some(y=> y.id === x.id));
Explanation:
filter method will call each and every element in the otherProducts array and check if the id of customerProduct is present in otherProducts for at least one element.
declare customerProducts , otherProducts as JS array variable and use JS Array filter find functions
let customerProducts = [
{
name: "foo",
id: 123
},
{
name: "test",
id: 44
}
]
let otherProducts = [
{
name: "other",
id: 44
},
{
name: "test",
id: 21
}
];
let filtered = customerProducts.filter( el => otherProducts.find( e => e.id == el.id) )
console.log(filtered);

Adding another property with Key Value in an object

I am sorry if this question already asked but i guess it confusing so i want to know how to add a property in an object which is not defined in the object.
I want to add a property name: 'something' in a nested objects.
let cars = {
passengers: null,
engine: {
yearBuilt: 2002,
model: "25481 AL"
}
now it has two properties passengers and engine. What i want is to add another property "name" in passengers and log it in an array with ['Alex', 'Mark']
What i tried:
cars.passengers = [{name: 'Alex'}]; //Output is like this [ { name: 'Alex' } ],
and when i add a square bracket notation in Alex only the output will be
name: [Object] }
cars.passengers = [{name: 'Alex'}]; //Output is like this [ { name: ['Alex'] } ] //Output is like { passengers: [ { name: [Object] } ]
code:
let newData = cars.passengers = [{name: ['Alex']}];
why its not showing in an array.? and how to do that .?
Can u try
cars.passengers = {name: ['Alex'] }

json object from javascript nested array

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

Send data from one array object into another array object

I've got an Object Array:
hm.push(member.personal);
console.log("New input: " + ko.toJSON(hm));
server.insertPersonalInformacion(ko.toJS(hm));
Console.log output:
[{
"personalInfo": {},
"adresaInfo": {},
"Telefone": [{
numer1: ,
callNumb:
}],
"Mobile": [{}],
"emailAdrese": [{
email:
}]
}]
Now i would like to place this Array Object into another Object:
var insertPersonalInformacion = function(inputInfo) {
memberData.personal.forEach(function(p) {
p.personalInfo.push(inputInfo);
"And here i am lost"
);
});
});
};
This is the call object
var memberData = {
personal: [{
"personalInfo": {},
"adresaInfo": {},
"Telefone": [{
numer1: ,
callNumb:
}],
"Mobile": [{}],
"emailAdrese": [{
email:
}]
}]
};
Your exact question is not quite clear, mainly because your variable identifiers seem a bit inconsistent throughout the code snippets.
If you want to assign your array to memberData.personal, a simple assignment will do:
var memberData = {
personal: yourArray
};
To merge the existing array content of memberData.personal with your array, use Array.prototype.concat():
var memberData.personal = memberData.personal.concat(yourArray);

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