I'm a JS beginner and I'm stuck with array/objects items.
I get a JSON file with a fetch request and I would like to extract a part of the data.
My data looks like this:
{
"profil": [
{
"name": "",
"id": ,
"city": "",
"country": "",
"tags": ["", "", "", ""],
"text": "",
"price":
},
So it's an object, which contain an array which contain a bunch of objects which contain a "tags" array....
I don't find a way to access tags items (without array index) with forEach loops...
My final purpose with this is to collect a single list of tags that exists in my object list.
How can I do this?
Using Array#flatMap:
const data = {
"profil": [
{ "tags": ["1", "2", "3", "4"] },
{ "tags": ["5", "6", "7", "8"] }
]
};
const tags = data.profil.flatMap(({ tags = [] }) => tags);
console.log(tags);
Edit: if you need the tags to be unique, you can use Set:
console.log([...new Set(tags)]);
Related
given code
[
{
"data": [
{
"text_name": "test",
"text_url": "https://www.news18.com/topics/gold-prices/1",
"is_new": "1"
},
{
"text_name": "test2",
"text_url": "https://www.news18.com/topics/gold-prices/2",
"is_new": "0"
}
],
"slug": "bollywood",
"heading": "testing",
"status": "1",
"is_open_new": "1",
"order_data": "2",
"section_dropdown": "bollywood"
}
]
I want to iterate through this given code snippet and get the data.
const trendingTopicsData = trendingTopics.data
but this is showing null
Since the object in the snippet is an array, first you have to get the index of the item you want to work with (in this case the first item — index 0). Then you can iterate through the data array however you want (loop, forEach, map etc.).
Try:
const trendingTopicsData = trendingTopics[0].data
Here it is as a runnable snippet:
const trendingTopics = [
{
"data": [
{
"text_name": "test",
"text_url": "https://www.news18.com/topics/gold-prices/1",
"is_new": "1"
},
{
"text_name": "test2",
"text_url": "https://www.news18.com/topics/gold-prices/2",
"is_new": "0"
}
],
"slug": "bollywood",
"heading": "testing",
"status": "1",
"is_open_new": "1",
"order_data": "2",
"section_dropdown": "bollywood"
}
]
// Get trending topics data array
const trendingTopicsData = trendingTopics[0].data;
console.log("Data array:", trendingTopicsData)
// Iterate through each of the items in the data array
trendingTopicsData.forEach((dataItem, index) => console.log(`Data item #${index}:`, dataItem));
The object you are trying to access is inside an array. You will have to loop through the array
trendingTopics.forEach(topic => {
// do something with topic.data
})
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.
What I want
I have 2 different Java-Script arrays/objects but with matching Ids. I want to merge them into a new object. So both the main object data and any matched elements from the secondary object are merged into a combined result.
What I tried
I tried using Object.assign() function but with no success.
Given Input
Example code, so I have 2 separate objects (main and lines):
let main = [
{
"Id": "1",
"Name": "Testing data"
}
]
let lines = [
{
"OtherId": "1",
"code": "AU-29830"
},
{
"OtherId": "1",
"code": "AU-29854-Single"
},
{
"OtherId": "1",
"code": "TV-BB21084623"
},
{
"OtherId": "2",
"code": "Don't Merge"
},
{
"OtherId": "3",
"code": "Don't Merge"
}
]
Expected Output
I want to merge those 2 arrays, so that the output should be a single array containing the merged main-object. This merged main-object should contain the original content of itself plus nested the filtered secondary array (only containing matching objects). The filtering was done using the id from the main array's object which has to match (the slightly deviating id) from each object of the secondary-array.
The resulting array should look like this:
let result = [
{
"Id": "1",
"Name": "Testing data",
"lines": [
{
"OtherId": "1",
"ProductCode": "AU-29830"
},
{
"OtherId": "1",
"ProductCode": "AU-29854-Single"
},
{
"OtherId": "1",
"ProductCode": "TV-BB21084623"
}
]
}
]
As your main is an array, I'm assuming you might end up with more than one main item in it. If so, here's one way to merge your line items onto each one:
const mergedMainItems =
main.map(mainItem=>({
...mainItem,
lines: lines.filter(line=>mainItem["Id"] === line["OtherId"])
}))
I think for this example this will work:
let result = [];
result.push({...main[0]}); //or even result.push(main[0])
result[0].lines = [];
for(let l in lines){
if(lines[l].code != "Don't Merge"){
result[0].lines.push({OtherId: lines[l].OtherId, ProductCode: lines[l].code})
}
}
I am developing a website with front-end and back-end separated. I used jquery to send request and get the result as a json object:
{
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
Now i am finding a way to get the data from the object user. How can i do it with javascript?
Complementing #arcs answer, remember that in Javascript you can access members of an object using dot notation (data.user[0].user_id) or square brackets notation. This way:
data['user'][0]['user_id']
this is useful because you can have a 'class' array and then do things like:
['item', 'shop', 'user'].forEach((array) => processArray(data[array][0]));
then you can filter only some classes or do more advanced stuff
When you have the data (in example it's in data) use the dot notation to get the node with the user.
The user is an array, so use [] to access a single element, e.g. [0]
var data = {
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
console.log( data.user[0].user_id )
I prefer use square brackets like this :
$jsonObject["user"][0]["user_id"]
but you can use the dot like this :
data.user[0].user_id
is the same thing.
If you want check if property exist you can do it :
if(typeof $jsonObject["user"] !== 'undefined'){
//do domethings as typeof $jsonObject["user"][0]["user_id"]
}
If you want get property dinamically you can do it :
const strId = "id";
const strName = "name";
//get user_id
let user_id = $jsonObject[user][0]["user_" + strId ];
//get user_name
let user_name = $jsonObject[user][0]["user_" + strName];
but there isn't very pretty.
I have array of object tree
var tree = [{
"id": "1",
"name": "one",
"child": [],
}, {
"id": "2",
"name": "two",
"child": [{
"id": "21",
"name": "twentyOne",
"child": [],
},{
"id": "22",
"name": "twentyTwo",
"child": [],
}],
}, {{
"id": "3",
"name": "three",
"child": [],
},
}].
Which one is the best way to store array of objects in localStorage?
Is it better to use another format?
There are several methods:
getItem
getAllItem
removeItem
saveItem
But there are child arrays of objects. It means that I will use recursive search to find necessary object.
Save the data in LocalStorage as an array, or array of simple objects, but try to keep it DRY (don't repeat yourself). For example, if you have a list of people, keep an array of the people, but don't keep a separate variable for the count.
What you want is basically a "state". As long as you keep it minimal you will be fine. Then you can use lodash or underscore to find, merge, add, remove elements from that array.