Add new section to Javascript object [duplicate] - javascript

This question already has answers here:
JavaScript - cannot set property of undefined
(8 answers)
Closed 1 year ago.
I have a JavaScript object customer that looks like this...
Object {
name: "John Doe",
age: "26"
}
I want to create a cars section and add some specifics so it looks like this...
Object {
name: "John Doe",
age: "26"
cars: {
car1 {
color: red,
type: ford
},
car2 {
color: blue,
type: GMC
},
car3 {
color: white,
type: toyota
}
}
}
I have tried to do this like this...
customer['cars']['car1'] = { color:'white', type:'toyota' }
But this gives me the error...
customer.cars is undefined
Where am I going wrong?
​

Problem
The error msg means that customer.cars has not been declared/assigned.
Solution
There are 2 options:
initialize empty cars object (In case that you want to assign each car)
var customer = {name:"John Doe",age:"26"};
customer.cars = {}; // init empty cars object
customer.cars.car1 = { color:'white', type:'toyota' };
customer.cars.car2 = { color:'blue', type:'GMC' };
console.log(customer);
assign all cars property directly.
var customer = {name:"John Doe",age:"26"};
customer.cars = {car1:{color:"red",type:"ford"},car2:{color:"blue",type:"GMC"},car3:{color:"white",type:"toyota"}};
console.log(customer);

You calling an undefined field cars on a customer record.
Try to define it first:
customer.cars = {}
And only then:
customer.cars.car1 = {...}
You can use [] syntax too:
customer['cars'] = {}

const obj = {
name: "John Doe",
age: "26"
}
obj.cars = {car1 : {color: 'white'}}
console.log(obj)
The way you're inserting the object is incorrect. See my example for the correct way to do this.

Related

How to create self-executing anonymous function in Object?

in my object
let obj = {
name:["Harry","Scren","Docis","Altab"],
age:[32,44,22,55]
}
I need to write down a self executing anonymous function in object that, when i call any member of the object it will execute that self executing anonymous function and it will check whether the length of both array (name and age) are equal or not, If not equal then throw an error .....I need to have something like
let obj = {
name:["Harry","Scren","Docis","Altab"],
age:[32,44,22,55],
(function(){
if(name.length != age.length){
throw new Error('both name and age 's length are not equal')
}
}()) // But this is not possible to create in object I have just showed down what I wanted to create
}
How to create something like that in javascript object ??
I'm not sure, but I think that's not possible...
But let me ask a question: why you have an obj containing two arrays? Hasn't more sense having an array of the obj which each element of the array contains one name and one age? I'll show you
const people = [
{ name: "Pearson 1", age: 20 },
{ name: "Pearson 2", age: 20 },
{ name: "Pearson 3", age: 20 },
{ name: "Pearson 4", age: 20 },
]
So you do not have to check the length since every obj has its own name and age field.

Destructuring nested objects in an array

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);

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'] }

Creation of a multi-level JSON string

I want to create a multi-level JSON string with JS.
Scenario
3 countries with 5 grandfathers with 3 kids which whom also have 3 kids that have 5 friends.
I get the data from a external JSON file that looks like this.
{"countries":[
{
"name":"USA",
"grandfathers":[
{
"gFName":"Steve",
"grandfathersKid":[
{
"gFKName": "Linda",
"kid": [{
"name": "Steve JR",
"friends": [{
"name": "Kriss|John|Martin|Steven"
}]
}
]
}
]
}
]
}
]}
And now I want to store some of the countries with people and their relatives and friends in a a new JSON list that looks exactly as the list made in the external json file. I aim to use this "homemade" list later on in the script.
My initial response for this was
var tree = new Array();
tree = {};
var countries = new Array();
countries[0] = "canada";
countries[1] = "USA";
countries[2] = "Mexico";
countries[0][0] = "Steve"; //Lives in Canada
countries[0][0][0] = "Linda"; //Daughter of Steve
countries[0][0][0][0] = "Steve JR"; // Kid of Linda
countries[0][0][0][0][0] = "Kriss"; //Steves Friend
...
$.each(countries...function(index, value){
tree[index].country = value;
$.each(grandfathers...function(key, value){
tree[index].country[key].grandfather = value;
}
And so on, but this is not giving me the result I want. What am I doing wrong? And a more effective way than to take each of everything?
Third edit...
Is this the sort of thing you're trying to do?
var countries = $.map(oldCountries || [], function(country) {
return {
name: country.name,
people: $.map(country.grandfathers || [], function(gpa) {
return {
name: gpa.gFName,
children: $.map(gpa.grandfathersKid || [], function(parent) {
return {
name: parent.gFKName,
children: $.map(parent.kid || [], function(kid) {
return {
name: kid.name,
friends: kid.friends
};
})
};
})
};
})
};
});
I wasn't sure what to do with the friends node. Should that be normalized into something more useful, or do you want to leave it alone?
This Fiddle demonstrates the technique.
I think we'd need to know more about your requirements. But several thing I see here are:
You declare tree and initialize it as an Array, then immediately reinitialize it as an
empty object
You are not creating the intermediate nodes here, such as tree[index] but just assuming
that they exist.
You are trying to assign the country[key] property of an object, using the dot-property
access.
Can you supply the countries structure and the grandfather's structure. And are they nested?
And finally, what would you like for the output format? The code above hints at it, but it's still a little fuzzy.
Edit
So are you trying to achieve a structure something like this?:
var countries = [
{
name: "Canada",
people: [
{
name: "Steve",
children: [
{
name: "Linda",
children: [
{
name: "Steve, Jr.",
friends: [
{
name: "Kriss"
}
//, more friends
]
}
//, more grandchildren
]
}
//, more parents
]
}
//, more grandparents
]
}
//, more countries
];
May be this jsfiddle can help you to get started?
And here is an example derived from your code.
Sounds like a homework, so I'll try to point you in the right direction. I think you are confusing objects and arrays. You could use a "country" object and a "person" object. A country object should have an array of person objects, as inhabitants. Person objects can have an array of person objects as descendants. Add a method like "addDescendant", which creates a new person under a person. From There you can build the structure as you like. Here is some pseudo code:
countries = [];
function Country(name){ this.name = name; this.population = [];}
function Person(kids){this.descendants = []; this.addDescendant = function(){...};
//loop from 1 to kids and add descendants as "new Person"
}
person = new Person(3);
country1 = new Country("MyCountry1");
// now add people to country1.population
countries.push(country1);
The final structure should look something like this:
countries = [
{ name: "country 1",
people: [{ name: "Steve"},
{name: "Clara", descendants: [{name: "Clara's daughter"},
{name: "Clara's son"}]
]}
},
{ name: "country 2",
people: [{}, {} ...]
}
];

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