Response object data using as array - javascript

I have to write map function based on response data but response data is not an array
example response
{
"data": {
"e680c823-895b-46f0-b0a0-5f8c7ce57cb2": {
"id": 98218,
......
},
"e24ed385-0b86-422e-a4cc-69064846e13b": {
"id": 98217,
.......
},
"c1cc583b-a2be-412b-a286-436563984685": {
"id": 118868,
.....
},
}
var posts = data.map(function (item) {
return item.id;
});
I have to achieve like this console
console.log( posts[1].id ) //98217

map over the Object.values and return the nested object.
const data = {
data: {
"e680c823-895b-46f0-b0a0-5f8c7ce57cb2": {
"id": 98218
},
"e24ed385-0b86-422e-a4cc-69064846e13b": {
"id": 98217
},
"c1cc583b-a2be-412b-a286-436563984685": {
"id": 118868
}
}
};
const posts = Object.values(data.data).map(obj => obj);
console.log(posts[1].id);

Object.values() returns an array of Object values. You can loop over them to get your desired result.
let respData = {
"data": {
"e680c823-895b-46f0-b0a0-5f8c7ce57cb2": {
"id": 98218
},
"e24ed385-0b86-422e-a4cc-69064846e13b": {
"id": 98217
},
"c1cc583b-a2be-412b-a286-436563984685": {
"id": 118868
}
}
}
var posts = Object.values(respData['data']).map(function (item) {
return item;
});
console.log(posts[0].id) //98218

Related

how to loop inside object array Angular

I want to display values from my json but I don't know how to do it. Is it possible to loop inside an object array ? i don't know if the keyvalue pipe can help me but I want to do without.
how to get the student2 and also the name to display it ?
thanks everyone.
json
{
"student": {
"student1": [],
"student2": [
{
"id": "123",
"name": "boot"
},
"student3": [],
]
},
"teacher": {
"teacher1": [],
"teacher2": [
{
"id": "123456",
"name": "toto"
},
]
}
}
ts.file
get(){
this.service.getAll().subscribe((data:any) => {
object.keys(data).length > 0;
})
}
Assuming your JSON object from your GET request looks like the one you posted above simply do:
get(){
this.service.getAll().subscribe((data:any) => {
data.student.forEach(element => {
for (let key in element) {
console.log(" key:", key, "value:", element[key]);
for (let val in element[key]) {
console.log(" value:", val);
}
}
});
})
}

Javascript for loop in shows undefined

MY JSON is:
[
{
"id": "5d7d855c-7301-4b2f-9676-3cb758316b4c",
"products": [
{
"id": 1,
"price": 699.0,
"quantity": 2,
"color": "silver",
"size": "128GB"
}
],
"contact": {
"name": "5423654",
"surname": "gdfsgsdf",
"address": "gfdsg",
"phone": "53454353",
"city": "5234532",
"country": "gfdsgfds"
},
"shippingPrice": 0.0,
"discount": null,
"totalPrice": 1398.0
}
]
I am trying to loop in it with for loop in
class Orders {
_orders;
constructor() {
this.init().then(() => this.renderOrders());
}
async init() {
this._orders = await this.getOrders();
}
GET(url) {
try {
return axios.get(url)
} catch (e) {
return e;
}
}
getOrders() {
return new Promise(resolve => {
this.GET('http://localhost:8080/orders/getOrders').then(response => {
resolve(response.data);
})
})
}
renderOrders() {
const template = document.getElementById("orders__template");
const container = document.getElementById("orders");
container.innerHTML = "";
console.log(typeof this._orders);
for (let key in this._orders) {
if (this._orders.hasOwnProperty(key)) {
for (let productKey in this._orders[key].products) {
if (this._orders[key].products.hasOwnProperty(productKey)) {
console.log(this._orders[key].products[productKey].id); //getting the id
}
}
for (let discountKey in this._orders[key].discount) {
if (this._orders[key].discount.hasOwnProperty(discountKey)) {
console.log(this._orders[key].discount[discountKey].id); //undefined(even when it's not null, why?
}
}
for (let contactKey in this._orders[key].contact) {
if (this._orders[key].contact.hasOwnProperty(contactKey)) {
console.log(this._orders[key].contact[contactKey].name); //undefined too
}
}
}
}
}
document.addEventListener("DOMContentLoaded", () => {
new Orders();
});
However, i am getting only at first for loop result, other discount, or contact are undefined.
i tried with other dummy data, i am getting the same results, so, what is the problem? However, i have other examples where it do work, the same structure, whats wrong?
in the orders object, property discount and contact are not arrays so you don't need to use for loop:
for (let key in order) {
if (order.hasOwnProperty(key)) {
for (let productKey in order[key].products) {
if (order[key].products.hasOwnProperty(productKey)) {
console.log(order[key].products[productKey].id); //getting the id
}
}
if (order[key].discount) {
console.log(order[key].discount.id);
}
if (order[key].contact) {
console.log(order[key].contact.name);
}
}
}

Loop through JSON array of objects and get the properties based on the matching IDs from objects

My target is if the id from digital_assets and products matches then get the value of URL fro digital_assets and ProductName from products object. I'm able to traverse through the object and get the values of digital_assets and products but need some help to compare these two objects based on IDs to get the value of URL and ProductName. Below is what I've done so far.
var data = [{
"digital_assets": [{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}]
}, {
"products": [{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},{
"id": ["BB002", "AA002"],
"ProductName": "PROD 555"
}]
}
];
$.each(data, function () {
var data = this;
//console.log(data);
$.each(data.digital_assets, function () {
var dAssets = this,
id = dAssets['id'];
// console.log(id);
});
$.each(data.products, function () {
var proData = this,
prod_id = proData['id'];
// console.log(prod_id);
$.each(prod_id, function () {
var arr_id = this;
console.log(arr_id);
});
});
});
Do I need to create new arrays and push the values into the new arrays? Then concat() these array to one. ? Bit lost any help will be appreciated.
Here is one way you can do this via Array.reduce, Array.includes, Object.entries and Array.forEach:
var data = [{ "digital_assets": [{ "id": "AA001", "url": "https://via.placeholder.com/150" }, { "id": "AA002", "url": "https://via.placeholder.com/150" } ] }, { "products": [{ "id": ["BB001", "AA001"], "ProductName": "PROD 485" }, { "id": ["BB002", "AA002"], "ProductName": "PROD 555" } ] } ]
const result = data.reduce((r,c) => {
Object.entries(c).forEach(([k,v]) =>
k == 'digital_assets'
? v.forEach(({id, url}) => r[id] = ({ id, url }))
: v.forEach(x => Object.keys(r).forEach(k => x.id.includes(k)
? r[k].ProductName = x.ProductName
: null))
)
return r
}, {})
console.log(Object.values(result))
You can use Array.prototype.find, Array.prototype.includes and Array.prototype.map to achieve this very gracefully.
let data = [
{
"digital_assets": [
{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},
{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}
]
},
{
"products": [
{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},
{
"id": ["BB002","AA002"],
"ProductName": "PROD 555"
}
]
}
];
// Find the 'digital_assets' array
let assets = data.find(d => d['digital_assets'])['digital_assets'];
// Find the 'products' array
let products = data.find(d => d['products'])['products'];
// Return an array of composed asset objects
let details = assets.map(a => {
return {
id : a.id,
url : a.url
name : products.find(p => p.id.includes(a.id)).ProductName
};
});
console.log(details);
changed answer to fit your needs:
var data = [
{
"digital_assets": [
{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},
{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}
]
},
{
"products": [
{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},
{
"id": ["BB002","AA002"],
"ProductName": "PROD 555"
}
]
}
]
let matchingIds = [];
let data_assetsObject = data.find(element => {
return Object.keys(element).includes("digital_assets")
})
let productsObject = data.find(element => {
return Object.keys(element).includes("products")
})
data_assetsObject["digital_assets"].forEach(da => {
productsObject["products"].forEach(product => {
if (product.id.includes(da.id)){
matchingIds.push({
url: da.url,
productName: product.ProductName
})
}
})
})
console.log(matchingIds);
working fiddle: https://jsfiddle.net/z2ak1fvs/3/
Hope that helped. If you dont want to use a new array, you could also store the respective data within the element you are looping through.
Edit:
I think i know why i got downvoted. My example works by making data an object, not an array. changed the snippet to show this more clearly.
Why is data an array anyway? Is there any reason for this or can you just transform it to an object?
Edit nr2:
changed the code to meet the expectations, as i understood them according to your comments. it now uses your data structure and no matter whats in data, you can now search for the objects containing the digital_assets / products property.
cheers
https://jsfiddle.net/2b1zutvx/
using map.
var myobj = data[0].digital_assets.map(function(x) {
return {
id: x.id,
url: x.url,
ProductName: data[1].products.filter(f => f.id.indexOf(x.id) > -1).map(m => m.ProductName)
};
});

Extract keys from object and nested array

I have an array of objects, those objects also have in some cases nested arrays, which contain objects.
Each object as a property key which I need to extract.
An example of the JSON I am dealing with is...
{
"items": [
{
"key":"main",
"foo":"bar",
"children":[
{
"key":"one",
"foo":"barboo"
},
{
"key":"two",
"foo":"boobaz"
}
]
},
{
"key":"secondary",
"foo":"baz",
"children":[
{
"key":"one",
"foo":"barboobaz"
},
{
"key":"two",
"foo":"boobazfoo"
}
]
}
]
}
Currently I am mapping over items and returning key, then where I find children I am mapping again returning key.
Something like this pseudo code...
class SomeClass {
let contentKeys = []
extractKeys = navItems => {
navItems.map(item => this.appendToContentRequest(item));
return this.contentKeys.join(',');
};
appendToContentRequest(item) {
if (~!this.contentKeys.indexOf(item.key)) {
this.contentKeys.push(item.key);
}
if (item.children) {
item.children.map(child => this.appendToContentRequest(child));
}
}
}
I don't like this though, it feels very 'hacky' and not very functional.
Is there a better way to achieve this?
You can use below recursive function to take any key's value of any nested array of objects
function extract(array, keyName) {
return array.reduce((a, b) =>
a.concat(...Object.keys(b).map(e => e === keyName ? b[e] : (Array.isArray(b[e]) ? extract(b[e], keyName) : null))), []).filter(e => e);
}
console.log(extract(obj.items, 'key'));
<script>
const obj = {
"items": [{
"key": "main",
"foo": "bar",
"children": [{
"key": "one",
"foo": "barboo"
},
{
"key": "two",
"foo": "boobaz"
}
]
},
{
"key": "secondary",
"foo": "baz",
"children": [{
"key": "one",
"foo": "barboobaz"
},
{
"key": "two",
"foo": "boobazfoo"
}
]
}
]
}
</script>
var data = {
"items": [
{
"key":"main",
"foo":"bar",
"children":[
{
"key":"one",
"foo":"barboo"
},
{
"key":"two",
"foo":"boobaz"
}
]
},
{
"key":"secondary",
"foo":"baz",
"children":[
{
"key":"one",
"foo":"barboobaz"
},
{
"key":"two",
"foo":"boobazfoo"
}
]
}
]
}
function flatNestedKey(array) {
var result = [];
const context = this;
array.forEach(function (a) {
result.push(a.key);
if (Array.isArray(a.children)) {
result = result.concat(context.flatNestedKey(a.children));
}
});
return result;
}
var keys = flatNestedKey(data.items);
console.log(keys);

How i can get data from another object?

Plunker
I have two structures - ingredients and recipes
[{
"id":"1",
"name": "Cucumber"
},
..
]
and
[{
"id":"1",
"name": "Salad1",
"recipein":[1, 3, 5]
}, {
...
}
]
and i want to show names of ingredients in each salad by press a button.
I filtered object to get ID of object, then i try to get a array of ingredients
getSalad(param:number) {
this.saladId = this.recipe.filter(rec => {
return rec.id.includes(param);
})
this.getNameOfIngredients(this.saladId)
}
getNameOfIngredients(saladArray:any) {
var ingredientsId = saladArray.map(function(num) {
return num.recipein;
});
i getting array [1,2,4] now i want to show all names of ingredients from this.ingredients with this array of id's.
How can i do this?
Plunker
I made updates in your plunker. I think thats what are you looking for: Plunker
getSalad(param:number) {
this.saladId = this.recipe.filter(rec => +rec.id === param )[0];
if(!this.saladId){
this.currentSalad = "Salad not found";
return;
}
this.currentSalad = this.getNameOfIngredients(this.saladId)
}
getNameOfIngredients(saladArray:any) {
return this.ingredients.filter( ing => {
return saladArray.recipein.indexOf(+ing.id) !== -1;
});
let _ingredients = []
this.ingredients.foreach((ingr)=>{
if(this.ingreIDArry.indexof(ingr.id) > -1){
_ingredients.push(ingr.name)
}
})
return _ingredients
is this what you want?
if you can flatten the array, it would be very straightforward for us to do lookups.
Here is what you could do.
const salads = [{
"id": "1",
"name": "Salad1",
"recipein": [1, 3, 5]
}];
const ingredients = [{
"id": "1",
"name": "Cucumber"
},
{
"id": "2",
"name": "Cucumber2"
},
{
"id": "3",
"name": "Cucumber3"
},
{
"id": "4",
"name": "Cucumber4"
},
{
"id": "5",
"name": "Cucumber5"
}
];
const flattenIngredients = (() => {
const output = {};
ingredients.forEach((ingredient) => {
output[ingredient.id] = ingredient;
});
return output;
})();
const getSalad = (saladId) => {
const filteredSalad = salads.filter((salad) => {
return saladId == salad.id;
});
if (filteredSalad.length > 0) {
const salad = filteredSalad[0];
return salad.recipein.map((receip) => flattenIngredients[receip].name);
}
}
console.log(getSalad(1));

Categories

Resources