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);
}
}
});
})
}
Related
I want to create a nested filter in js
when I filter my array primary data is affected and changed but I need preliminary data to remove filters
my js code :
let result = companies;
result.map((item, i) => {212
let rows = [...result[i].table.table_rows].filter((item3) => {
return Object.keys(item3).some(i => item3[i][key] === value[key]);
});
result[i].table.table_rows = [...rows];
return result[i];
});
arrayFilter(result);
my data is:
{
"companies": [
{
"company": {
"name": "company 1"
},
"table": {
"table_rows": [
{
"cells": {
"product_name": "prod1",
"pa_size": "12"
}
},
{
"cells": {
"product_name": "prod2",
"pa_size": "15"
}
}
]
}
},
{
"company": {
"name": "company 2"
},
"table": {
"table_rows": [
{
"cells": {
"product_name": "prod2-1",
"pa_size": "12"
}
},
{
"cells": {
"product_name": "prod2-2",
"pa_size": "18"
}
}
]
}
}
]
}
I tried many ways to solve this problem, but I did not get the right answer
Your question is not clear, the point I have understand that you wanted to filter the array "table_rows" located inside each companies array object? map and filter returns new array, so the solution for this is:
result = result.companies.map((item, i) => {
const newItem = {...item};
let rows = newItem .table.table_rows.filter((item3) => {
return Object.keys(item3).some(i => item3[i][key] === value[key]);
});
newItem.table_rows = [...rows];
return newItem ;
});
arrayFilter(result);
I have following JSON data, If any one of the child name is matching with any of the parent name then i want to create new json set.
var PARENT_CHILD = {
'Newton': ['Plato', 'Aristotle'],
'Aristotle': ['Einstein'],
'Plato': ['Tesla', 'Edison'],
'Einstein': ['Hawking']
};
I want to convert it into like below:
{
"Newton": {
"child": "Plato, Aristotle"
},
"Plato": {
"parent": "Newton",
"child": "Tesla, Edison"
},
"Aristotle": {
"parent": "Newton",
"child": "Einstein"
},
"Einstein": {
"parent": "Aristotle",
"child": "Hawking"
},
"Tesla": {
"parent": "Plato"
},
"Edison": {
"parent": "Plato"
},
"Hawking": {
"parent": "Einstein"
}
}
You can use Array.reduce on the entries in PARENT_CHILD, creating a new entry in the output for the parent (if it doesn't already exist) and adding the child array to it, and then creating a new entry (with parent property) for each of the children of that parent:
var PARENT_CHILD = {
'Newton': ['Plato', 'Aristotle'],
'Aristotle': ['Einstein'],
'Plato': ['Tesla', 'Edison'],
'Einstein': ['Hawking']
};
var result = Object.entries(PARENT_CHILD).reduce((acc, [parent, child]) => {
if (acc[parent]) {
acc[parent].child = child.join(', ');
}
else {
acc[parent] = { child : child.join(', ') };
}
child.forEach(name => acc[name] = { parent });
return acc;
}, {});
console.log(result);
hey I have a file of a JSON data like this called data.json:
"servers":
{
"sv-123344":
{
"owner": "id",
"vstats": false
},
"sv-44332211":
{
"owner": "id",
"vstats": false
}
},
"users":
{
"uid-111222":
{
"favlist":
[
"1",
"2",
"3"
]
},
"uid-445566":
{
"favlist":
[
"1",
"2",
"3"
]
}
}
So Basicly i want 3 Functions that i dont know how to write them
1- i need a function to check that if an input is exist in favlist of a user or not
like this: if(checkExist(userid, input) == true)
2- i need a function to add the input to the favlist
like this: addFav(userid, input)
3- and i need a remove function to remove the input from the favlist
like: removeFav(userid, input)
so i would be so thankfull if anyone can help me with this codes
and all the credits will go to anyone who helps me
Your JSON Object is missing some {} also to be able to remove data from array/object you need you use array function like filter and map
js={"servers":{ "sv-123344": { "owner": "id", "vstats": false }, "sv-44332211": { "owner": "id", "vstats": false } }, "users": { "uid-111222": { "favlist": [ "1", "2", "3" ] }, "uid-445566": { "favlist": [ "1", "2", "3" ] } } }
function checkfav(userid,input){
var bool
Object.entries(js.users).forEach(o=>{
if(o[0]==userid){
var inp=input.toString()
bool= o[1].favlist.includes(inp)
}
})
return bool
}
function addtofav(userid,input){
var ar
Object.entries(js.users).forEach(o=>{
inp=input.toString()
if(o[0]==userid)
o[1].favlist.push(inp)
ar=o[1].favlist
})
return ar
}
function removeFav(userid, input){
var arr
Object.entries(js.users).forEach(o=>{
inp=input.toString()
if(o[0]==userid){
if(o[1].favlist.includes(inp)){
o[1].favlist.splice(o[1].favlist.indexOf(inp),1)
}
arr=o[1].favlist
}
})
return arr
}
console.log(checkfav(1))
console.log(addtofav("uid-445566",9))
console.log(removeFav("uid-111222",2))
1.) Your JSON is malformed. you need to surround everything with {} like this:
{
"servers":
{
...
},
"users":
{
...
}
}
So if your favlist is let favlist = [1, 2, 3] then you can use favlist.includes(value) to see, if your favlist contains an input. Just let your checkExists function return the result of this function.
Since your favlist is an array, you can use favlist.push(value) to add values to your array. It does not check for duplicates though.
To remove a specific value from an array, you need to locate the index of that value. Use the following:
/* if value = 2 and favlist = [1,2,3], then this gives index = 1 */
let index = favlist.findIndex(x => x === value);
favlist.splice(index, 1);
Just keep in mind to take care of possible duplicates.
I'm trying return an object from the code below that has the key value pair of name:sparky and return the entire metadata and stats array for that object.
I don't want to use Object.values(objectArray)[0] because this data is coming from an API and I expect the objects position in the array to change in the future.
I've tried objectArray.find but I don't know how to use that to find a value of an array which is inside another array. The value for name will always be unique and the actual objectArray has many more objects inside of it.
Help would be greatly appreciated!
Code
objectArray = [
{
"metadata": [
{
"key": '1',
"name": "sparky"
}
],
"stats": [
{
"statsFieldOne": "wins"
},
{
"statsFieldTwo": "kills"
}
]
},
{
"metadata": [
{
"key": '1',
"name": "abby"
}
],
"stats": [
{
"statsFieldOne": "wins"
},
{
"statsFieldTwo": "kills"
}
]
}
]
Desired result
{
"metadata": [
{
"key": '1',
"name": "sparky"
}
],
"stats": [
{
"statsFieldOne": "wins"
},
{
"statsFieldTwo": "kills"
}
]
}
I guess you can do following:
function getObjectForName(key, name) {
var filteredMetadata = [];
for(var i=0; i< objectArray.length; i++) {
filteredMetadata = objectArray[i].metadata.filter((val) => val[key] === name)
if(filteredMetadata.length) {
return objectArray[i];
}
}
}
getObjectForName('name', 'sparky')
What this code basically does is, iterates through all objects and check if name is sparky, if yes just break it. If you want to return all occurrences matching name, you need to add all of them to another array and return it.
You can simply use Reduce
let objectArray = [{"metadata":[{"key":'1',"name":"sparky"}],"stats":[{"statsFieldOne":"wins"},{"statsFieldTwo":"kills"}]},{"metadata":[{"key":'1',"name":"abby"}],"stats":[{"statsFieldOne":"wins"},{"statsFieldTwo":"kills"}]}]
let op = objectArray.reduce(( op,{metadata,stats} ) =>{
let found = metadata.find(({name})=>name==='sparky')
if(found){
op.push({metadata:found,stats})
}
return op
},[])
console.log(op)
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)
};
});