Get all string values from a nested object - javascript

I have an object, with nested objects. How do I target a specific index of the object and loop through all the nested values of image. As you will note the length of the nested objects vary.
Target example: productArray[0].image = test1.png, test2.png, test3.png
var products = [
//item1
{
identifier: "item-0",
image: {
"img1": "test1.png",
"img2": "test2.png",
"img3": "test3.png"
}
},
//item2
{
identifier: "item-1",
image: {
"img1": "test1.png",
"img2": "test2.png"
}
},
//item3
{
identifier: "item-2",
image: {
"img1": "test1.png",
"img2": "test2.png",
"img3": "test3.png",
"img4": "test4.png",
"img5": "test5.png",
"img6": "test6.png",
"img7": "test7.png"
}
}
];

We can do this. What you need to do is a simple loop through the object at a specific index, or you can target them all. Note that the image object is not an array, so it will not have an accurate length property.
Target all indexes:
for(var i = 0; i < products.length; i++) {
console.log("Item: " + i);
var images = products[i].image;
for(var a in images)
console.log(images[a]);
}
Target specific:
for(var i in products[0].image)
console.log(products[0].image[i]);
I used a for loop here, but you can use a while loop if you would like.
example

Steps:
You need to iterate over your original array of products. products
Each element (product) will be in format { identifier: "", image : {"img1" : "img2", ..}} products[i]
You get the image property of current product - this is an object. products[i].image
Now you need to iterate over the properties of the image object. products[i].image[j]
Code:
for(var i = 0; i < products.length; i++)
{
for(var j in products[i].image)
{
// Here you have all the images for the current product.
// You can print them, group them or whatever you want to do with them
console.log(products[i].image[j]);
}
}
Also you can change the code (introduce variables) to be more readable.

var strs = (function( obj ) {
var ret = [];
for( im in obj ) {
ret.push( obj[im] );
//You could access each image URL here
//ad strs in the end will have all of them
//comma-separated after this code completes
// im is the key, obj[ im ] the value
}
return ret.join(',');
})( products[0].image );
console.log( strs );
WORKING JS FIDDLE DEMO

Here is another way of doing this, with newer functions in ECMAScript 5
var images = Object.keys(products[2].image).map(function(key){
return products[2].image[key]
})
console.log(images) // Returns: ["test1.png", "test2.png", "test3.png", "test4.png", "test5.png", "test6.png", "test7.png"]
How It Works:
Object#keys returns an array of key names. Array#map creates a new array using the keys from Object#keys. By looking up the key from the object you get the value, which will be the image name.
JS FIDDLE

Related

How to create a new array from multiple arrays

I'm trying to somewhat combine 3 arrays to create a new one. So the end result is
<li>array1[0]array2[0]array3[0]</li>
I tried a for loop but it ends up with 27 answers and there should only be 2 with the data I have.
// const ingredientsList = () => {
// for (let i = 0; i < recipe.ingredients.length; i++) {
// for (let j = 0; j < recipe.size.length; j++) {
// for (let k = 0; k < recipe.amount.length; k++) {
// console.log(recipe.amount[k], recipe.size[j], recipe.ingredients[i]);
// <li>
// {recipe.amount[k]}
// {recipe.size[j]}
// {recipe.ingredients[i]}
// </li>;
// }
// }
// }
// };
I would greatly appreciate anyone's help. I'm currently working in reactjs. Each array is the same length. I have 3 arrays: ingredient list, amount, and size. So I want to combine them so they read smoothly such as "1 cup flour"
The way you are looping through the three arrays will end up as such (in pseudo code):
Loop through the first array and for every element:
Loop through the second array and for every element:
Loop through the third array and
for every element create a list item of each element at index n from
each array.
Since I am not sure exactly what you are wanting I will have to assume they are the same length arrays so you can do:
for(let i = 0; i < recipe.amount.length; i++) {
console.log(`${recipe.amount[i]} ${recipe.size[i]} ${recipe.ingeredients[i]}`)
}
This should get you logging the appropriate results, then just create the html list elements.
If I understand correctly based on the code in the question, you have three arrays (ingredients, size, amount).
If each of the arrays is the same length and each index's data corresponds to the data at the same index of the others, you could write a loop using the length of one of them and pass the same index into each array like...
for (let i = 0; i < recipe.ingredients.length; i++) {
console.log(
recipe.ingredients[i],
recipe.size[i],
recipe.amount[i],
);
}
Seeing as you're working in react though, if you have control over the data yourself, it would probably make more sense to store each instruction in an object in a recipe array, then map over that array and create the list item like...
Somewhere in the component could be something like...
this.recipe = [
{
ingredient: 'something',
amount: 'some amount',
size: 'some size',
},
{
ingredient: 'something',
amount: 'some amount',
size: 'some size',
},{
ingredient: 'something',
amount: 'some amount',
size: 'some size',
}
]
and in the template...
{
recipe.map((instruction) => (
<li>
{ instruction.amount }
{ instruction.size }
{ instruction.ingredient }
</li>
));
}
const emp1 = ["Cecilie", "Lone"];
const emp2 = ["Emil", "Tobias", "Linus"];
const allEmp = emp1.concat(emp2);
you can try using concat keyword to merge arrays. In case of more than two arrays you can use
emp3 = ["john", "lacy"]
const allEmp = emp1.concat(emp2, emp3);

Null Values in array of objects

I am creating objects when textbox having some values (using ng-blur and textbox.value!==undefined) and then putting these objects in an array (all working fine here).
When I click on checkbox (checkbox model bind with textbox ng-required) I need to delete that particular object having that textbox value.
I am using:
arr.splice(index,1);
to remove that particular object from array (by matching it's name like "monthly" or "quarterly" etc.), but it is creating null at that particular position.
for e.g. [object,object,object]
[
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
]
after removing all element it shows [] and when I add another new object it displays [3:object] and it's content as [null,null,null,object];
or
if I remove middle object say name:"quarterly", it shows [object,object] but after adding a new object it display array as [object,object,null,object] with length of array as 4.
Why is there null and how can I remove that from array. (don't want to iterate again to check null).
It is difficult to say why your code creates the null values without have a look to it.
But I can say you that it is not the expected behaviour.
You can see this example to get some inspiration:
var data = [
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
];
var newObjectToBeAdded = { name: "daily", amount:"100" }
function showObjects()
{
document.body.innerHTML += data + '<hr>';
}
function deleteObjectByName( objectName )
{
for( var i = 0; i < data.length; i++ )
{
if( data[ i ].name == objectName )
{
data.splice(i, 1);
}
}
}
function addObjectToData( newObject )
{
data.push( newObject );
}
showObjects();
deleteObjectByName( "quarterly" );
showObjects();
addObjectToData( newObjectToBeAdded );
showObjects();
Just to throw a guess out, maybe you are accidentally duplicating the array. Maybe in some point of your code you are doing something like this:
var new_array = original_array.splice( index );
Or creating the new array in the loop you use to find the target object, or using some kind of intermediate array, etc.
Hope it helps!
var arrayWithoutNulls = myArray.filter(function(val) {
if (val) {
return val;
}
});

Javascript arrays

Let's suppose I have an associative array like this one
var client1={
"id":"1"
"category":"Interiorism",
"photo1":"img/ClientCorp/photoClient1.jpg",
"photo2":"img/ClientCorp/photoClient2.jpg",
"photo3":"img/ClientCorp/photoClient3.jpg",
"photo4":"img/ClientCorp/photoClient4.jpg",
};
var client2={
.
.
.
};
allClients=[client1, client2..., clientx];
I want to set up a function that pushs the photo keys in an empty array. The problem is that not all the clients have the same number of photos, so I am using 'for'. Here is the function I wrote
function photoKeys()
{
var keyList=Object.keys(allClients[id]);
var numKey=parseInt(listaKeys.length);
var photoAlbum=[]; //here I want to put the photo URL's
for (i=2; i<=numFotos; i++)
{
????????????
}
}
Here is the problem, how I can write the photo object from the client array whith the i var from the 'for' function?
I tried this but didn't work
for (i=2; i<=numFotos; i++)
{
photoAlbum.push(allClients[id].photo+'i');
}
Your current code would be parsed like this:
photoAlbum.push(allClients[id].photo + 'i');
It would try to evaluate allClients[id].photo and then append the string i. You need to access the property name using bracket notation instead of dot notation.
You also have the symbol and string part backward, photo is the string and i is your index variable.
photoAlbum.push(allClients[id]['photo' + i]);
The big thing to understand is that client in your example isn't an array, it's an object.
var client1={
"id":"1"
"category":"Interiorism",
"photo1":"img/ClientCorp/photoClient1.jpg",
"photo2":"img/ClientCorp/photoClient2.jpg",
"photo3":"img/ClientCorp/photoClient3.jpg",
"photo4":"img/ClientCorp/photoClient4.jpg",
};
You can acquire an object's keys as an array using Object.keys(client1), or you can loop through all an object's keys using for...in syntax.
If you want to feed an arbitrary number (numFotos) of property values from your object into an array called photoAlbum, you can use the following syntax:
var i = 0;
for(var key in client1){
photoAlbum.push(client1[key]);
if(++i >= numFotos){
break; // break out of the loop if i equals or exceeds numFotos
}
}
First of all you should be accessing the photo paths like:
photoAlbum.push(allClients[id]['photo' + i]);
But i would really recommend you to change the format of your client object to something like this:
var client1 = {
"id" :"1"
"category" :"Interiorism",
"photos" : [
"img/ClientCorp/photoClient1.jpg",
"img/ClientCorp/photoClient2.jpg",
...
]
};
Or this, if you need to store those "photo1", "photo2" ids:
var client2 = {
"id" :"1"
"category" :"Interiorism",
"photos" : [
{
"id" : "photo1",
"path" :"img/ClientCorp/photoClient1.jpg"
},
...
]
};
Then you can iterate them way easier like this:
for(var i = 0; i < allClients[id].photos.length; i++){
photoAlbum.push(allClients[id].photos[i]);
//or this for the second format:
//photoAlbum.push(allClients[id].photos[i].path);
}

How do you update the properties of an object in javascript?

How do you update the properties of an object in javascript?
I would to update "id" of 68917 distance from 8.8 to 4.5...
I have access to lodash.js
[
{
"_id":68917,
"Distance":8.81,
"Lat":"42.65322175",
"Lon":"-73.77398886"
},
{
"_id":131277,
"Distance":"9.86",
"Lat":"42.654658",
"Lon":"-73.805866"
},
{
"_id":62450,
"Distance":6.58,
"Lat":"42.67457566",
"Lon":"-73.74902171"
}]
your_object[0].Distance = 4.5;
If you don't know the index beforehand:
_.findWhere(your_object, {'_id': 68917}).Distance = 4.5;
The code you have provided provides an array. If this is is representative of your code, you can then iterate over the objects in the array using a for loop:
If you assign the provided code to a variable named array, you can use this code to iterate over the items in the array.
Once you do that, you can then access the properties of the objects inside using the dot operator, locating and updating the correct item.
function echo (text){
document.getElementById("output").innerHTML += text + "<br/>"
}
var array = [
{
"_id":68917,
"Distance":8.81,
"Lat":"42.65322175",
"Lon":"-73.77398886"
},
{
"_id":131277,
"Distance":"9.86",
"Lat":"42.654658",
"Lon":"-73.805866"
},
{
"_id":62450,
"Distance":6.58,
"Lat":"42.67457566",
"Lon":"-73.74902171"
}];
echo("First item's distance " + array[0].Distance);
for(var i = 0; i < array.length; i++){
if(array[i]._id === 68917){
echo("Found item "+array[i]._id);
array[i].Distance = 4.45;
}
}
echo("First item's distance " + array[0].Distance);
I created a JS Fiddle that demonstrates this solution works;
http://jsfiddle.net/gB5Nn/2/
You could use the built-in "filter" function to get the item you want.
someObject.filter(function(item){return item._id === 68917;})[0].Distance = 4.5;
Here is an example:
http://jsfiddle.net/aVBx8/

Delete an element inside a JSON array by value with jQuery

Part of my json Array
var videos = $j.parseJSON('
[
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"private",
"id":"803641223" },
{ "privacy":"public",
"id":"1300612600" }, ......
When I console.log the element I'm getting
[Object, Object, Object, …]
0: Object
privacy: "public"
id: "1169341693"
1: Object
privacy: "private"
id: "803641223"
2: Object
privacy: "public"
id: "1300612600"
I also have a unique id I want to search for
var uniqueId = 803641223;
I want to find, in my videos array, the right id, and delete that whole array element. So In that case, I want my final videos array to contain only 2 object, instead of 3 :
var videos = $j.parseJSON('
[
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"public",
"id":"1300612600" }, ......
My problem is how to get in the array to do my splice. I prefer to do it with jQuery
Any help please?
You can use grep :
videos = $.grep(videos, function(e) { return e.id!='803641223' });
In vanilla JavaScript you could have used the similar filter function but it's not supported by IE8.
Please note that videos is a JavaScript array, it's not a JSON array, even if it was made by parsing a JSON string.
A non-jQuery solution that modifies the array in place:
var uniqueId = 803641223;
var videos = [
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"private",
"id":"803641223" },
{ "privacy":"public",
"id":"1300612600" }
];
function cleaner(arr, id) {
for (var i = 0; i < videos.length; i++) {
var cur = videos[i];
if (cur.id == uniqueId) {
arr.splice(i, 1);
break;
}
}
}
cleaner(videos, uniqueId);
http://jsfiddle.net/4JAww/1/
Note that this modifies the original array in place, such that the original videos array will have the items you want, and the one that matched the uniqueId will be gone (forever). So it depends on whether you want to be able to access the original array ever again, or are okay with modifying it.
It just loops through the elements of the array, compares the item's id property to the uniqueId value, and splices if they match. I use break; immediately after the splice because you seem to imply that the uniqueId can/should only appear once in the array since it's...unique.
Hello you can remove element with javascript splice function...
videos.items.splice(1, 3); // Removes three items starting with the 2nd,
It worker for me.
arrList = $.grep(arrList, function (e) {
if(e.add_task == addTask && e.worker_id == worker_id) {
return false;
} else {
return true;
}
});
It returns an array without that object.
Hope it helps.

Categories