{
"comments": [
{
"created_utc": 1622513325,
"text": "gdhg sgf sddsfsd fdsf"
},
{
"created_utc": 1622513188,
"text": "sfdg sgf fdgfdg"
}
]
}
How would you iterate over each object to see the text?
Something like..?
let data = fs.readFileSync(path.resolve(__dirname, 'comments.json'));
let comments = JSON.parse(data);
for(var i in comments){
for(var j in i) {
console.log("? " + j.text)
}
}
If you know the structure of your JSON will always be a comments object on the first level, containing a list of elements with created_utc and text, you can do as easy as the following code.
You don't need to nest the cycle as you only want to iterate over one list, then read the items and directly access to the text field of each item.
var jsonString = `{
"comments": [
{
"created_utc": 1622513325,
"text": "gdhg sgf sddsfsd fdsf"
},
{
"created_utc": 1622513188,
"text": "sfdg sgf fdgfdg"
}
]
}`;
let comments = JSON.parse(jsonString).comments;
comments.forEach(comment => {
console.log(comment.text);
});
Related
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);
}
}
});
})
}
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)
I have the following Foods Object:
var Foods = {
"Fruits": [{
"id": "1",
"Name": "Granny Smith",
"Category": "1"
}, {
"id": "2",
"Name": "Raspberries",
"Category": "1"
}
],
"Potatoes": [{
"id": "3",
"Name": "Maris Piper",
"Category": "2"
}, {
"id": "4",
"Name": "Charlotte",
"Category": "2"
}]
}
What I would like to do is only push the produce that matches an id passed by a link.
Get Foods
This is what I have tried so far:
function getCat (id){
result = [];
for(let item in Foods) {
if(Foods[item].id == id) {
data[item].foreach(v=>result.push("<div class='box'><h2>" +
data[key].Name + "<br></div>"));
}
}
}
display();
function display() {
alert(result);
}
So if a user hits the link (which has an id of 2), the result array should contain "Charlotte" and "Maris Piper" but I am just drawing a blank.
Any help appreciated.
Cheers
Youre quite close, however theres a slight problem:
for(let item in Foods) {
console.log(Foods[item]);
/*
[{
"id": "1",
"Name": "Granny Smith",
"Category": "1"
}, {
"id": "2",
"Name": "Raspberries",
"Category": "1"
}
]
*/
So youre iterating over the categories, which are arrays.
Foods[item].id
is undefined as its an array and not a product. So we need to iterate the array to, e.g.
var result=[];
Object.values(Foods).forEach(function(category){
category.forEach(function(product){
if(product.id===id){
result.push(product);
}
});
});
Run
But if youre doing this quite often, it might be easier to create one product array once:
var products = Object.values(Foods).reduce((arr,cat)=>arr.concat(cat),[]);
So you can simply filter this whenever someone clicks a button:
var result = products.filter(product=>product.id === id);
Run
You're somewhat on the right track, but what's data? Why are you not doing anything with result? And you should be looking at the Category property rather than ID.
This'll work:
function getCat(id) {
let result = [];
for (let item in Foods) {
if (Foods.hasOwnProperty(item)) {
Foods[item].forEach((food) => {
if (food.Category == id) {
result.push(food);
}
});
}
}
console.log(result);
}
First of all result array should be at global scope so that you can access it in another function, And in object you are having categories then each category has some data in array so after iterating over object, you need to iterate the items from array as well to get the value. Check the below code.
var result = [];
function getCat(id){
for(let item in Foods) {
var foodItem = Foods[item];
for(let i=0; i<foodItem.length; i++){
if(foodItem[i].id == id) {
result.push("<div class='box'><h2>" + foodItem[i].Name + "<br></div>"));
}
}
}
}
function display() {
alert(result);
}
display();
Iterator is wrong. You should do it like this:
function getCat(id){
result = [];
for(let item in Foods) {
Foods[item].forEach(function(each){
if(each.id == id) { // you cmpare to the wrong target
// do something
}
});
}
}
I have a JSON data like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
},
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
}
}
I need to search for fuzzy data and merge. For example InvestmentsDeposits and InvestmentsDeposits$$$d need to be merged because it matches closely in name
Need to use javascript for this
For now I can make sure source data will always have $$$d at the end to merge with the target data without $$$d i.e., InvestmentDeposits.
My final merged content should be like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
"text": "newtext"
}
]
}
}
}
any help on this one?
What I have tried so far
var json0 = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
}
};
var json1 =
{
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
};
// Merge object2 into object1, recursively
$.extend( true, json0, json1 );
I am able to merge the data if i am able to split the InvestmentDeposits and InvestmentDeposits$$$d in to two distinct JSON objects but how to split and move the $$$d data in to another object? to make the jquery extend work
Use Object.keys() to find an object's keys and figure out what data to move over. You can compare the first key with the others to find matches, then remove the keys you just looked at until all of them are gone. Here's an example with a similar object.
var dat = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}, "InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
},
"NotLikeTheOthers": {
"Um": "Yeah."
}
};
var result = {}; // This will be the merged object
var keys = Object.keys(dat); // Contains keys
while(keys.length) {
var i=1;
for(; i<keys.length; i++) { // Find matches
if(keys[0] == keys[i] + '$$$d') { // Match type 1
result[keys[i]] = dat[keys[i]]; // Copy orig
for(var j in dat[keys[0]]) { // Replace values
result[keys[i]][j] = dat[keys[0]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
} else if(keys[i] == keys[0] + '$$$d') { // Reverse matched
result[keys[0]] = dat[keys[0]];
for(var j in dat[keys[i]]) {
result[keys[0]][j] = dat[keys[i]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
}
}
if(i > 0) { // Didn't find a match
result[keys[0]] = dat[keys[0]];
keys.shift();
}
}
alert(JSON.stringify(result));
Note that Object.keys() requires IE9+.
I'm using javascript with a json library and running into a little trouble. Here's my json output:
{
"artist": {
"username": "myname",
"password": "password",
"portfolioName": "My Portfolio",
"birthday": "2010-07-12 17:24:36.104 EDT",
"firstName": "John",
"lastName": "Smith",
"receiveJunkMail": true,
"portfolios": [{
"entry": [{
"string": "Photos",
"utils.Portfolio": {
"name": "Photos",
"pics": [""]
}
},
{
"string": "Paintings",
"utils.Portfolio": {
"name": "Paintings",
"pics": [""]
}
}]
}]
}
}
In javascript I'm trying to access the entries in the map like so:
var portfolios = jsonObject.artist.portfolios.entry;
var portfolioCount = portfolios.length;
for ( var index = 0; index < portfolioCount; index++ )
{
var portfolio = portfolios[index];
txt=document.createTextNode("Portfolio Name: " + portfolio['string'] );
div = document.createElement("p");
div.appendChild ( txt );
console.appendChild(div);
}
but portfolios is "undefined". What's the correct way to do this?
Look at your JSON results. portfolios is a one-element array; portfolios[0] is an object containing a single key, entry, which maps to an array of two objects that have both string and utils.Portfolio keys. Thus, the syntax jsonObject.artist.portfolios.entry will not work. Instead, you want jsonObject.artist.portfolios[0].entry.
If possible, I would suggest changing whatever code generates those JSON results to remove the entry level of indirection entirely, e.g. like so:
{
"artist": {
/* ... */
"portfolios": [
{
"string": "Photos",
"utils.Portfolio": {
"name": "Photos",
"pics": [""]
}
},
{
"string": "Paintings",
"utils.Portfolio": {
"name": "Paintings",
"pics": [""]
}
}
]
}
}
Then you could access it with
var portfolios = jsonObject.artist.portfolios;
for (var i = 0, portfolio; portfolio = portfolios[i]; ++i)
{
// use portfolio variable here.
}
There is an array in your object. I believe you're looking for this:
var portfolios = jsonObject.artist.portfolios[0].entry;
The portfolios property is an array, so you need to use an index to get the first element:
var portfolios = jsonObject.artist.portfolios[0].entry;