How to add a new object to another within an array [duplicate] - javascript

This question already has answers here:
How to append something to an array?
(30 answers)
Closed 2 years ago.
I have an array which looks like this:
array = [
{code1:
{
number: 2,
name: "e"
}
},
{code2:
{
number:2,
name: "u"
}
}
]
and I want to add the following as a new object to say "code1" without changing the data it now has.
{
number: 3,
name: "j"
}
how can I do it? Thank you!

1st approach
If I understood what you want to do correctly this could work:
array = [
{code1:
{
number: 2,
name: "e"
}
},
{code2:
{
number:2,
name: "u"
}
},
{code1:
{
number: 3,
name: "j"
}
}
];
2nd approach
However this would make the structure more difficult to traverse. As an alternative you could make the whole thing into a dictionary of arrays, like this:˛
let object = {//doesn't matter what we call it
code1:[
{
number:2,
name: "e"
},
{
number:3,
name: "j"
}
],
code2:[
{
number:2,
name: "u"
}
]
};
You'd go about accessing the new object like this: console.log(object.code1[0].number);
You can try this approach out in the snippet bellow.
let object = {//doesn't matter what we call it
code1:[
{
number:2,
name: "e"
},
{
number:3,
name: "j"
}
],
code2:[
{
number:2,
name: "u"
}
]
};
console.log(object.code1[0].number);
Closing statement
But as I've already said, I'm not sure if I understood your question correctly, I'd suggest editting the question to make it clearer in the future.
Thanks for reading
Internet person out.

Related

get first 2 charater from an object using JS [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
i wanted represent first two letters of phone number,i want to get phone numbers first two characters. what i have tried is below Get first two of attribute and find target based on it.
let object = [
"key": {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
}]
what i have tried is below
object[0].substr(0,2);
let test = {
key: {
"login-attempt": 1,
name: "ADMIN",
phone: "0777123456",
}
};
console.log(test.key.phone.substr(0,2));
You're more likely to have an object like this:
let object = {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
};
In this case, your code might be:
let prefix = object.phone.substr(0,2);
Or you might have an array of objects:
let object = [
{
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
},
{
login-attempt: 1
name: "CLERK"
phone: "2222222222"
}
];
You can get the 1st two characters of the second element like this:
let prefix = object[1].phone.substr(0,2);
If the element was nested within "key":
let object = {
key: {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
}
};
let prefix = object.key.phone.substr(0,2);
And so on...

Why is my object formulating differently in the console than it is when I run it through Tidy JS?

My Array of Objects is not appearing the way I want it to when I print it to the console. When I put it through Tidy JS, it formats it correctly. When I print it to the console, it looks incorrect.
What I want it to look like is:
Array
Object
Key:Value
Key:Value
Array
Object
Object
Object
Object
But instead its prints out how it does in this codepen:
https://codepen.io/anon/pen/qLrgKg
Any ideas as to why formatting it like it is in this codepen instead of how I want it to be?
var ArrayOfBlocks1 = [
{
ID:"1",
block: "block1",
BlockElements: [
{ blockElement1: { QuestionID: "1" } },
{ blockElement2: { QuestionID: "2" } },
]
},
{
ID:"2",
block: "block2",
BlockElements: [
{ blockElement1: { QuestionID: "1" } },
{ blockElement2: { QuestionID: "2" } }
]
},
{
ID:"3",
block: "block3",
BlockElements: [
{ blockElement1: { QuestionID: "1" } },
{ blockElement2: { QuestionID: "2" } }
]
}
];
You are printing the first element in the array rather then the whole array.
Change line 42 from console.log(ArrayOfBlocks1[0]) to console.log(ArrayOfBlocks1)

How to acess a complex JSON [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I am a beginner and, as I began to increase the complexity of JSON, I started to confuse myself by accessing it. How do I access the following JSON? I would like to access the value and keys of the services
{
employers:{
Mike: {
old: 20,
services:{
cut : {
value : 10
}
hair_straightening : {
value: 20
}
}
}
Penny: {
old: 20,
services:{
cut : {
value : 10
}
hair_straightening : {
value: 20
}
}
}
}
}
Everyone has to start somewhere :)
I'm not sure if I completely understand what you're after, but here goes...
First off, it looks like your notation on your object is subtly off when listing your keys. For example, between Mike and Penny you should have a comma separating each of those keys in the larger employers object.
Something like:
employers: {
Mike: {
...
}, //need a comma here
Penny: {
...
}
}
Also, within each of those employers, there should be a comma between the keys for cut and hair_straightening.
services: {
cut: {
value: 10
}, //need a comma here
hair_straightening: {
value: 20
}
}
Now to your actual question...
To get the keys for each of the services, you can use Object.keys(). This function would get you they keys for a given employer. Then you can also grab the values from inside that same function. (Note this is for only one employer; you'd just want to iterate over both and use this same function on each)
function getServices(employer) {
var services = employer.services;
var servicesKeys = Object.keys(services);
var serviceValueMatrix = [];
servicesKeys.forEach(function(service) {
serviceValueMatrix.push([service, employer.services[service].value])
})
return serviceValueMatrix;
}
// assuming you had var yourJSON = { employers: {...} }
// getServices(yourJSON.employers.Mike);
// returns [["cut",10], ["hair_straightening",20]]
Also, given that your JSON object is already in key:value format, you could probably skip the last set of objects in the format of value: 10, value: 20 etc, and instead just make the last tier of your object something like:
services:{
cut: 10,
hair_straightening: 20
}
Then you could just grab services.cut and services.hair_straightening.
Full code below for clarity:
const yourJSON = {
employers: {
Mike: {
old: 20,
services: {
cut: {
value: 10
},
hair_straightening: {
value: 20
}
}
},
Penny: {
old: 20,
services: {
cut: {
value: 10
},
hair_straightening: {
value: 20
}
}
}
}
}
function getServices(employer) {
var services = employer.services;
var servicesKeys = Object.keys(services);
var serviceValueMatrix = [];
servicesKeys.forEach(function(service) {
serviceValueMatrix.push([service, employer.services[service].value])
})
return serviceValueMatrix;
}
console.log(getServices(yourJSON.employers.Mike));
// returns [["cut",10], ["hair_straightening",20]]
your json should look something like this:
{
employers:[
{
name: "Mike",
age: 20,
services: [
{name:"cut",value:10},
{name:"hair_straightening",value:20}
]
},{
name: "Penny",
age: 20,
services: [
{name:"cut",value:10},
{name:"hair_straightening",value:20}
]
}
]
}
You can use Object.keys to get the keys of an object as an array, then you can loop through that nicely.
// in this case json is a variable representing your parsed data
Object.keys(json).map(function(key) {
console.log(json[key])
return json[key].services
})
That would give you an array of services objects.

How to delete Object from deep javascript array? [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 6 years ago.
I want to delete object from my array posted below but nothing works. If I delete the properties it just goes to undefined. I have a recursive function that returns to me the right object. I wish to delete the second object and his children.
var data = {
parameters: [
{
id: 0,
name: "First",
value: "1",
children: []
},
{
id: 1,
name: "Second",
value: "2",
children: [
{
id: 2,
name: "Third",
value: "3",
children: []
}
]
}
],
index: 3
}
You could use Array#splice.
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
data.parameters.splice(1, 1)
// index // \\ length

How to include elements of an array in another array?

So for example I have a MAIN array with all the information I need:
$scope.songs = [
{ title: 'Reggae', url:"#/app/mworkouts", id: 1 },
{ title: 'Chill', url:"#/app/browse", id: 2 },
{ title: 'Dubstep', url:"#/app/search", id: 3 },
{ title: 'Indie', url:"#/app/search", id: 4 },
{ title: 'Rap', url:"#/app/mworkouts", id: 5 },
{ title: 'Cowbell', url:"#/app/mworkouts", id: 6 }
];
I want to put only certain objects into another array without typing in each of the objects so the end result will look like
$scope.array1 = [
{ title: 'Reggae', url:"#/app/mworkouts",id: 1 },
{ title: 'Cowbell', url:"#/app/mworkouts",id: 6 }
];
I have tried this with no luck:
$scope.array1 = [
{ $scope.songs[1] },
{ $scope.songs[6] }
];
I will have to do a bunch of these so typing in each object would take forever, is there any faster way to do this? Thanks in advance :)
You need to do something like this:
$scope.array1 = $scope.songs.filter(function (song) {
return (song.title == "Reggae" || song.title == "Cowbell");
});
Here, the filter function will give you a filtered new array to be replaced for the original scope value.
Or in simple way, using the array indices, you can use:
$scope.array1 = [ $scope.songs[0] , $scope.songs[5] ];
You need to remove the braces since it's already an object. Although the array index starts from 0 so change index value based on 0.
$scope.array1 = [
$scope.songs[0] ,
$scope.songs[5]
];

Categories