get specific value from json file by Id - javascript

Im using the $.get to get JSON file content which is working fine,currently I want to filter and get the item with Id 4 (the last one) ,how should I do that ?
in the Jquery doc I didn't find some hint to it...
http://api.jquery.com/jquery.get/
this is the code:
$.get('tweets.json');
this is the JSON file content
[
{
"id": 1,
"tweet": "OMG, worst day ever, my BF #BobbyBoo dumped me",
"usersMentioned": [
{
"id": 10,
"username": "BobbyBoo"
}
]
},
{
"id": 2,
"tweet": "OMG, best day ever, my BF came back to me"
},
{
"id": 3,
"tweet": "OMG, worst day ever, just don't ask"
},
{
"id": 4,
"tweet": "#BobbyBoo OMG...just OMG!",
"usersMentioned": [
{
"id": 10,
"username": "BobbyBoo"
}
]
}
]
update
Currenlty when I try the following I dont get anthing in the then(function (tweets) ,tweets is emtpy
the value entry4 is filled with the correct value...
$.get('profile.json').then(function (profile) {
$('#profile-pre').html(JSON.stringify(profile));
$.get('tweets.json', null, null, 'json')
.then(function (response) {
var entry4 = response.filter(function (tweet) {
return tweet.id === 4;
})[0];
return entry4 ;
})
}).then(function (tweets) {
$('#tweets-pre').html(JSON.stringify(tweets));
var myFriend = $.get('friend.json');
return myFriend
}).then(function (friend) {

That would be
$.get('tweets.json',null,null,'json')
.then(function(response){
var iAmNumberFour = response.filter(function(tweet){
return tweet.id === 4;
})[0];
});
Added the type since if you don't pass the right headers, jQuery won't parse the JSON for you.
$.get('profile.json').then(function(profile) {
$('#profile-pre').html(JSON.stringify(profile));
return $.get('tweets.json', null, null, 'json')
.then(function(response) {
var entry4 = response.filter(function(tweet) {
return tweet.id === 4;
})[0];
return entry4;
})
}).then(function(entry4) {
$('#tweets-pre').html(JSON.stringify(tweets));
var myFriend = $.get('friend.json');
return myFriend
})

Related

Response object data using as array

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

How to create a JS object and append it to an array

I have the following data :
const data=
{
"1": [
{
"sales_project_id": 5,
"sales_project_name": "name",
"sales_project_est_rev": "123.00",
"project_status": {
"id": 1,
"label": "Start",
"description": null
}
},
{
"sales_project_id": 6,
"sales_project_name": "name2",
"sales_project_est_rev": "123.00",
"project_status": {
"id": 1,
"label": "Start",
"description": null
}
}
],
"2": [],
"4": []
}
These data are grouped in my backend based on their Status , in this case im only showing 2 status , but they are dynamic and can be anything the user defines.
What i wish to do is to transform the above data into the format below :
const data =
{
columns: [
{
id: // id of status here,
title: //label of status here,
cards: [
{
id : //sales_project_id here,
title: //sales_project_name here,
},
]
},
{
id: // id of status here,
title: //label of status here,
cards: [
{
id : //sales_project_id here,
title: //sales_project_name here,
},
]
}
]}
My guess would be to iterate over the data , however i am pretty unfamiliar with doing so , would appreciate someone's help!
Here is what i could come up with so far:
const array = []
Object.keys(a).map(function(keyName, keyIndex) {
a[keyName].forEach(element => {
#creating an object of the columns array here
});
})
after some trial and error , manage to accomplish this , however , im not sure if this is a good method to do so.
Object.keys(projects).map(function(keyName, keyIndex) {
// use keyName to get current key's name
// and a[keyName] to get its value
var project_object = {}
project_object['id'] = projects[keyName][0].id
project_object['title'] = projects[keyName][0].label
project_object['description'] = projects[keyName][0].description
console.log( projects[keyName][1])
var card_array = []
projects[keyName][1].forEach(element => {
var card = {}
card["id"] = element.sales_project_id
card["title"] = element.sales_project_name
card["description"] = element.sales_project_est_rev
card_array.push(card)
});
project_object["cards"] = card_array
array.push(project_object)
})
Im basically manipulating some the scope of the variables inorder to achieve this
See my solution, I use Object.keys like you, then I use reduce:
const newData = { columns: Object.keys(data).map((item) => {
return data[item].reduce((acc,rec) => {
if (typeof acc.id === 'undefined'){
acc = { id: rec.project_status.id, title: rec.project_status.label, ...acc }
}
return {...acc, cards: [...acc.cards, { id:rec.sales_project_id, title:rec.sales_project_name}]}
}, {cards:[]})
})}
See full example in playground: https://jscomplete.com/playground/s510194
I'd just do this. Get the values of data using Object.values(data) and then use reduce to accumulate the desired result
const data=
{
"1": [
{
"sales_project_id": 5,
"sales_project_name": "name",
"sales_project_est_rev": "123.00",
"project_status": {
"id": 1,
"label": "Start",
"description": null
}
},
{
"sales_project_id": 6,
"sales_project_name": "name2",
"sales_project_est_rev": "123.00",
"project_status": {
"id": 1,
"label": "Start",
"description": null
}
}
],
"2": [],
"4": []
};
const a = Object.values(data)
let res =a.reduce((acc, elem)=>{
elem.forEach((x)=>{
var obj = {
id : x.project_status.id,
title : x.project_status.label,
cards : [{
id: x.sales_project_id,
title: x.sales_project_name
}]
}
acc.columns.push(obj);
})
return acc
},{columns: []});
console.log(res)

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)
};
});

How to convert JSON object to array of String and number in JavaScript

I have the following response from a GET request to an API end point:
{
"success": true,
"data": {
"categories": [
{
"id": 1,
"label": "Default",
"url": "default",
"num_of_subs": 0
},
{
"id": 2,
"label": "Pet Grooming",
"url": "pet-grooming",
"num_of_subs": 2
},
],
}
}
Here is the fetch code:
const sendRegisterData = fetch('https://sg.cuzzey.com/api/listings/categories', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.text())
.then((responseText) => {
var response_final = JSON.parse(responseText);
if (response_final.success) {
this.setState({
categories: response_final.data.categories,
})
}
})
What I want to do, is to get the data from the categories and print them out as String and number (id and num_of_subs as number, label and url as String). Here is what I did:
const category_options = this.state.categories.map(category => {
return [<Text key={category.id} style={styles.smallTextBox}> {category.id} {'\n'}</Text>,
<Text key={category.label} style={styles.smallTextBox}> {category.label} {'\n'}</Text>,
<Text key={category.num_of_subs} style={styles.smallTextBox}> {category.num_of_subs} {'\n'}</Text>]
})
<ModalDropdown options={category_options} onSelect={(idx, label) => this.getCategory(idx, label)}>
<Text style={styles.smallTextBox}> {this.state.selected_category} </Text>
</ModalDropdown>
I used this code to get the value of id, label and num_of_subs:
getCategory = (idx, value) => {
this.setState({ category_id: value[0], selected_category: value[1], numSubs: value[2] })
}
When I print out category_id, selected_category and numSubs, the values are correct. However, they are object types and not String/number. I want to manipulate the values but I don't know how to convert them into String/number. I have tried using String(), Number(), parseInt(), JSON.parse(), toString() but none seems to work as they all result in "object" when I print out the typeof of the values.
Can I ask is there a way to solve this?
Your code is not working because you are not iterating through the array of objects. You are simply returning the object of arrays. This is why you cannot extract the value
var items = [{
"success": true,
"data": {
"categories": [{
"id": 1,
"label": "Default",
"url": "default",
"num_of_subs": 0
},
{
"id": 2,
"label": "Pet Grooming",
"url": "pet-grooming",
"num_of_subs": 2
},
],
}
}]
setState = [];
var catagories = items.map(x => x.data.categories);
catagories = catagories.reduceRight(x => x.cantact([]));
getCategory = (values) => {
for (let value of values) {
setState.push({
category_id: value.id,
selected_category: value.label,
numSubs: value.num_of_subs
})
}
}
var output = getCategory(catagories)
var results = setState.filter(x => x.numSubs > 0)
console.log(results);

How to hide object property to display using angular ng-model?

I want to hide _id to display on UI using ng-model , I see alot of examples of filtering data using ng-repeat but i did not find angular solution to achieve this task using ng-model.How can hide _id property to display ?
main.html
<div ng-jsoneditor="onLoad" ng-model="obj.data" options="obj.options" ></div>
Ctrl.js
$scope.obj.data = {
"_id": "58a3322bac70c63254ba2a9c",
"name": "MailClass",
"id": "MailTask_1",
"createdBy": "tyuru",
"__v": 0,
"properties": [{
"label": "Java Package Name",
"type": "String",
"editable": true,
"binding": {
"type": "property",
"name": "camunda:class"
},
"$$hashKey": "object:29"
}],
"appliesTo": [
"bpmn:ServiceTask"
]
}
var json = {};
function loadCurrentUserAndTemplate() {
AuthService.getCurrentUser()
.then(function(resp) {
$scope.currentUser = resp.data.id;
// console.log($scope.currentUser);
userTemplate($scope.currentUser);
});
}
loadCurrentUserAndTemplate();
$scope.obj = {
data: json,
options: {
mode: 'tree'
}
};
var privateFields = removePrivateFields($scope.obj.data, ['_id', '__v']);
// add private fields back to $scope.obj.data before POST
var modifiedData = Object.assign({}, $scope.obj.data, privateFields);
function removePrivateFields(obj, props) {
var output = {};
props.forEach(function(prop) {
if (obj.hasOwnProperty(prop)) {
output[prop] = obj[prop];
delete obj[prop];
}
});
return output;
}
function userTemplate(user) {
// console.log('inside template',$scope.currentUser);
templateService.getUserTemplates(user)
.then(function(response) {
// console.log('userTemplate',response.data);
// console.log(response.data.length);
$scope.displayedTemplates = response.data;
if (response.data.length !== 0 && response.data !== null) {
$scope.obj.data = response.data[0];
}
}
you can create a function like removePrivateFields to strip the private fields from original object and attach them back to the modified object before submitting to server
// for testing
var $scope = { obj: {} };
var jsonData = {
"_id": "58a3322bac70c63254ba2a9c",
"name": "MailClass",
"id": "MailTask_1",
"createdBy": "tyuru",
"__v": 0,
"properties": [{
"label": "Java Package Name",
"type": "String",
"editable": true,
"binding": {
"type": "property",
"name": "camunda:class"
},
"$$hashKey": "object:29"
}],
"appliesTo": [
"bpmn:ServiceTask"
]
};
var privateFields = removePrivateFields(jsonData, ['_id', '__v']);
// private fields got removed form actual jsonData
$scope.obj.data = jsonData;
console.log($scope.obj.data);
// once edit
// add private fields back to $scope.obj.data before POST
var modifiedData = Object.assign({}, $scope.obj.data, privateFields);
console.log(modifiedData);
function removePrivateFields(obj, props) {
var output = {};
props.forEach(function(prop) {
if (obj.hasOwnProperty(prop)) {
output[prop] = obj[prop];
delete obj[prop];
}
});
return output;
}
It would be both more performant and along Angular best practices to instead delegate this functionality into your controller or the service fetching the object.
Ideally, you want to perform any object manipulation or formatting within an Angular service, but you could also do it within your controller (probably fine if you're just instantiating your JSON editor with mock data).

Categories

Resources