Delete object items from an array - javascript

I have an object element and an array element which contains some items of the object.
I would like to delete the items in the object referenced by the array.
var array = ["test1","test2"];
var object =
...
"test1": {
"na": [
"t",
"t-t",
"t-98",
"t"
]
},
"test2": {
"python": [
"jjj"
]
}
...
When I use
delete object.test1
It works.
However in my case, I want :
for(var i = 0 ; i < array.length ; i++){
delete object.array[i];
}
But I got :
object.array is undefined
Any ideas ?
Fiddle

Use object[array[i]], object.array does not exist
If you are using lodash or underscore you can also use the _.omit function.
object = _.omit( object, array )

You would need to use array object notation.
delete object[array[i]]
Array notation is the only way to retrieve property values if you are indexing using a string value.

Related

creating an array, convert it to json and pass it to php

I want to fill an array dynamically with javascript, then convert it to a json string and pass it to php to deal with it.
The problem:
When I define the array like -code 1- the output is as expected:
var feld = {
"key1" : "1",
"key2" : "2",
"key3" : "3"
};
for (key in feld) { console.log (key + "= " + feld[key]); }
var jsonString = JSON.stringify(feld);
console.log(jsonString);
OUTPUT:
key1= 1
key2= 2
key3= 3
{"key1":"1","key2":"2","key3":"3"}
If I define the array like -code 2-
var feld = new Array ();
feld["key1"]="1";
feld["key2"]="2";
feld["key3"]="3";
for (key in feld) { console.log (key + "= " + feld[key]); }
var jsonString = JSON.stringify(feld);
console.log(jsonString);
OUTPUT:
key1= 1
key2= 2
key3= 3
[]
which means, that with code -2- there is nothing to pass to php.
what's wrong ?
"-code 1-" is not an array, it's a non-array object. "-code 2-" is an array, but being used as a non-array object. (And the reason you don't see your non-array properties when you stringify it is that since it's an array, JSON.stringify only serializes the array entries, not the non-array properties.)
What's wrong is that if you want an array, you need to create an array:
var feld = ["1", "2", "3"];
But it sounds like you don't want an array, you really do want an object, like in your first example. If you convert that to JSON and send it to your server, use json_decode to decode it into a PHP object where you can access the key1, key2, and key3 properties to get their values.
You are confusing arrays in js with arrays in php. If in php you can define literal keys for an array like this:
<?php
$a = array( 'key1' => 1);
$a['key1] === 1
in js that is the equivalent of an object rather than an array.
Js is more mathematichal , if you like, with the concept of array,
a = [2, 4, 6];
it is just a list of values/ objects each given by a numeric index.
a[1] === 4
In JavaScript you can attach properties to an array, which will not be member of this array. For example:
let array = new Array(); // Creates empty array: []
array[0] = 123; // Inserts a member to array
console.log(array) // Will output: [123]
array["abc"] = 789 // Attaches a property to array
console.log(array) // Will output: [123], no members were added to array
console.log(array.abc) // Will output: 789
This is possible because Array also acts as an object, so it has members (indexed) and also properties (having keys).
Arrays do not have keys (key0,key2,key3,...), only indexes (0,1,2,...). You probably want either a map or an array. The map is created by code you have attached to the question (first section), the array can be created as following:
var feld = new Array ();
feld[0]="1";
feld[1]="2";
feld[2]="3";
var jsonString = JSON.stringify(feld);
console.log(jsonString);
You have to objectify your array:
...
feld = Object.assign({}, feld);
var jsonString = JSON.stringify(feld);
...

How can i add a new object property to existing object in javascript?

I have an array of objects, let's say array[object,object....] . I want to add a new property to each object inside an array.
Below i have mentioned and existing array and the resulted one which i want.
Existing array :
array[ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf",}
{"name":"Brijesh mishra","add":"jkfhgfbrfhiurf"} ]
I want this array :
array[ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf","mobile":"95937338373"}
{"name":"Brijesh mishra","add":"jkfhgfbrfhiurf","mobile":"78984983498"} ]
How can i do this ?
You can do like this. Let there be an array of mobile number whose length is same as the length of array. Loop through the array array and add the mobile key and value from mobNum array
var mobNum=[1,2];
var array = [{
"name": "Siddhesh mishra",
"add": "hjhjjdjkhjibf"
}, {
"name": "Brijesh mishra",
"add": "jkfhgfbrfhiurf"
}]
array.forEach(function(item,index){
item.mobile=mobNum[index]
})
console.log(array)
var data = [ {"name":"Siddhesh mishra","add":"hjhjjdjkhjibf"},
{"name":"Brijesh mishra","add":"jkfhgfbrfhiurf"} ];
data.map(function(entry){
//add logic to get mobile number from entry.name or entry.add
return entry.mobile = '98989898';
})
console.log(data);

Get key values in JSON array

I'm trying to get the key values of each record in a JSON array when looping through it. Currently I have a simple JSON object like this:
"users": {
"key_11": {
"text": "11"
},
"key_22": {
"text": "22"
},
"key_33": {
"text": "33"
}
}
My current script uses the 'map' method to convert this JSON objet to a loop-able array:
var user_profiles_array = $.map(user_profiles_string, function(el) { return el; });
for (var xt = 0; xt < user_profiles_array.length; xt++) {
console.log(user_profiles_array[xt].text); //11 or 22
}
My question is, how can I get the value for e.g: 'key_11' or 'key_22'?
Thanks!
you can use Object.keys to get an array of all of your object's keys. Once you have that array, you can use Array.forEach to iterate over it as necessary:
Object.keys(usersObject).forEach(function(key, keyIndex) {
console.log("index:",keyIndex,"key:",key,"value:",usersObject[key]);
});
But!
your particular problem here is being caused by using $.map instead of JSON.parse. $.map returns an array, so of course your keys are always going to be numerical array indices - 0, 1, 2, and so on. You're not going to be able to use hash keys to find things in the array returned by $.map. Furthermore, judging by your variable names you're calling $.map on a string which is definitely not going to do what you want. Assuming you figure that part out and you somehow get a valid JavaScript object, and you still need to use $.map() for some reason, what you can do is this:
// $.map will return an array...
$.map(user_profiles_object, function(objVal, objKey) {
// ...and each item in that array will be an object with a
// property named 'key' and a property named 'val'
return {
key: objKey,
val: objVal
};
}).forEach(function(arrayObj) {
// now each item in the array created above will be an object
// created by your callback function:
console.log(arrayObj.key,":",arrayObj.val);
});
You can also rely on Js's foreach.
// JSON string must be valid. Enclose your JSON in '{}' (curly braces);
var user_profiles_string = '{ "users": { "key_11": { "text": "11" }, "key_22": { "text": "22" }, "key_33": { "text": "33" }}}';
var user_profiles_array = JSON.parse(user_profiles_string);
// For retrieval in loop, the Js foreach asigns the key to index param (i in this case).
for (i in user_profiles_array.users) {
// i is the key of the user currently iterated.
console.log('Key name is: ' + i);
// Use i as the index to retrieve array value.
console.log(user_profiles_array.users[i]);
}
// For direct retrieval using any given known key:
console.log(user_profiles_array.users['key_11']);

add object to another array of objects in javascript

Can any one please help me how to add objects to another array of Objects
myArray = [
{
"A" :{
values
},
"B" :{
values
},
"C":{
values
}
}
]
another Object:
{
"D":{
values
},
"E":{
values
}
}
I want to add next objects like D and E to My Array of First Object.
it shuold be like this
[
{
"A":{},
"B":{},
"C":{},
"D":{},
"E":{}
}
]
Cna you help me any one how to add this objects
Thanks in Advance
According to my understanding you have one array of object i.e.
myArray = [{"A" :{},"B" :{},"C":{}}]
and you want to add some property in that object so just use
myArray[0].D={};
myArray[0].E={};
console.log(myArray[0]);
And if You want to add more objects in Array use push method
var obj={"A1" :{},"B1" :{},"C1":{}}
if you want to add in myArray then use
myArray.push(obj);
yours array of object will be
myArray = [{"A" :{},"B" :{},"C":{}},
{"A1" :{},"B1" :{},"C1":{}}]
Hope it clears yours doubt.
try something like this
myarray=[{"A":"e1"},{"B":"e2"},{"C":"e4"}];
var obj={"D":"e5"};
myarray.push(obj);
alert(myarray[3].D)
will alert e5
DEMO
Update :
myarray=[{"A":"e1"},{"B":"e2"},{"C":"e4"}];
var obj={"D":"e6","E":"e9"};
myarray.push(obj);
alert(myarray[3].F)
will alert e9

Is there a way to get number of elements from object?

Let me explain in detail. I have below an object with me -
{
"OBJECT1" : {
"NAME1" : "VALUE1",
"NAME2" : "VALUE2",
"NAME3" : "VALUE3"
},
"OBJECT2" : {
"NAME4" : "VALUE4",
"NAME5" : "VALUE5"
}
}
From this object, I want to get something like number of elements in OBJECT1 = 3 and number of elements in OBJECT2 = 2. If at all this is possible using javascript.
Basically what I am trying to do is, to loop through the name value pairs available in the object dynamically so that if someone adds another element to object, I don't have to change my code.
Also any alternative is also ruled out since I am allowed to only use object in my use-case.
Without converting your object you could iterate through the object counting properties like so:
function countObjectProperties(obj)
{
var count = 0;
for(var i in obj)
if(obj.hasOwnProperty(i))
count++;
return count;
}
Expanding on why you need to use hasOwnProperty as I said in the comment below you can run into an issue where a library or browser has added methods and properties to Objects, in order to avoid counting these we check for hasOwnProperty before counting it. More details at MSDN or at Mozilla Developer Center
For JSON string that represent an object (which is your case), you cannot use any length property. you need to loop through the object (see Kristoffer S Hansen's answer).
If it represented an array, you could get the length with:
var len = arr.length;
JQuery makes it simpler:
var len = $(JSON).length;
To answer your broader goal, as specified in your question:
For looping through the properties, you can use the for..in construct:
for (var item in myobject) {
// some browsers add more properties to every object, we don't want those
if (myobject.hasOwnProperty(item)) {
do_something(item);
}
}
Assuming that myobject is the object in your question, this will loop through it and call do_something(OBJECT1) and do_something(OBJECT2); you can use the same construct to loop through the child objects:
// loop through OBJECT1 and OBJECT2
for (var item in myobject) {
// some browsers add more properties to every object, we don't want those
if (myobject.hasOwnProperty(item)) {
// loop through the item's children
for (var pair in item) {
if (item.hasOwnProperty(pair)) {
// each of the name:value pairs will be passed to this
do_something_else(item,pair);
}
}
}
}

Categories

Resources