Get specific value from an object and push it into an array - javascript

Hello I have an obj(came from JSON parsed) and I'm trying to get only one value from it the "VALUE"(default.timelineData)
for example from this obj I want an array [38,35,87,63,34].
I tried with Object.values and also to pass it to an array and then work with it but it's very complicated and I believe there is a shortcut to it. function without success hopes for help thanks...
{
"default":{
"timelineData":[
{
"time":"1610323200",
"formattedTime":"Jan 11, 2021",
"formattedAxisTime":"Jan 11",
"value":[
38
],
"hasData":[
true
],
"formattedValue":[
"38"
]
},
{
"time":"1610409600",
"formattedTime":"Jan 12, 2021",
"formattedAxisTime":"Jan 12",
"value":[
35
],
"hasData":[
true
],
"formattedValue":[
"35"
]
},
{
"time":"1610496000",
"formattedTime":"Jan 13, 2021",
"formattedAxisTime":"Jan 13",
"value":[
87
],
"hasData":[
true
],
"formattedValue":[
"87"
]
},
{
"time":"1610582400",
"formattedTime":"Jan 14, 2021",
"formattedAxisTime":"Jan 14",
"value":[
63
],
"hasData":[
true
],
"formattedValue":[
"63"
]
},
{
"time":"1610668800",
"formattedTime":"Jan 15, 2021",
"formattedAxisTime":"Jan 15",
"value":[
34
],
"hasData":[
true
],
"formattedValue":[
"34"
]
}
],
"averages":[
]
}
}

The property you are trying to access is an Array. You can use Array.map to iterate through the elements and push the returned values into a new array at the same time. Like this:
const values = obj.default.timelineData.map(item => item.value[0])
console.log(values); // [38, 35, 87, 63, 34]

Related

Group object values by date

I'm trying to make an upcoming event on react native, I have this object
const calendatData = [
{
"data": [
{
"id": 25,
"title": "Spotify",
"name": "Family",
"service_id": 1,
"repetition": "Monthly",
"price": "79000",
"upcoming_date": [
"2020-08-07T13:35:44.606Z"
]
},
{
"id": 26,
"title": "Netflix",
"name": "Mobile",
"service_id": 2,
"repetition": "Monthly",
"price": "49000",
"upcoming_date": [
"2020-08-18T13:35:44.600Z",
"2020-08-07T13:35:44.606Z"
]
},
{
"id": 27,
"title": "iTunes",
"name": "Weekly Special",
"service_id": 3,
"repetition": "Weekly",
"price": "22000",
"upcoming_date": [
"2020-08-07T13:35:44.606Z",
"2020-08-14T13:35:44.606Z",
"2020-08-21T13:35:44.606Z",
"2020-08-28T13:35:44.606Z"
]
}
],
"status": "success"
}
]
what I've been trying to do is to extract that object based on the upcoming_date.
the result that I need is like this
upcomingData = [
{
date: '2020-08-07',
title: [
'Spotify',
'Netflix',
'iTunes'
]
},
{
date: '2020-08-18',
title: ['Netflix']
},
{
date: '2020-08-14',
title: ['iTuunes']
},
{
date: '2020-08-21',
title: ['iTuunes']
},
{
date: '2020-08-28',
title: ['iTuunes']
}
]
On the same date, if there are multiple titles, it should be grouped under the same date in the object.
instead what I got was this object
upcomingData = [
{
title: [
"Spotify",
"Netflix",
"iTunes",
],
date : [
"2020-08-29",
"2020-08-07",
"2020-08-18",
"2020-08-07",
"2020-08-07",
"2020-08-14",
"2020-08-21",
"2020-08-28",
]
}
]
I am new to this, and I'm aware that this is mostly about javascript knowledge, any help would be appreciated.
thanks
The ideas are:
First, iterate your object by Array.prototype.map() and set a unique map key from the converted date.
Then push the title to every map's key.
Actually your final map(here is myMap) will be your expected upcomingData. To output as your expected object, you can make it in your own way.
const calendarData = [{ "data": [{ "id": 25, "title": "Spotify", "name": "Family", "service_id": 1, "repetition": "Monthly", "price": "79000", "upcoming_date": ["2020-08-07T13:35:44.606Z"] }, { "id": 26, "title": "Netflix", "name": "Mobile", "service_id": 2, "repetition": "Monthly", "price": "49000", "upcoming_date": ["2020-08-18T13:35:44.600Z", "2020-08-07T13:35:44.606Z"] }, { "id": 27, "title": "iTunes", "name": "Weekly Special", "service_id": 3, "repetition": "Weekly", "price": "22000", "upcoming_date": ["2020-08-07T13:35:44.606Z", "2020-08-14T13:35:44.606Z", "2020-08-21T13:35:44.606Z", "2020-08-28T13:35:44.606Z"] }], "status": "success" }];
var myMap = new Map();
calendarData[0].data.map(element => {
var dates = [];
element.upcoming_date.map(date => {
var upcoming_date = date.slice(0,10);
if (!myMap.get(upcoming_date)) {
myMap.set(upcoming_date, []);
}
dates.push(upcoming_date);
});
var len = dates.length;
for (let i = 0; i < len; i++) {
myMap.get(dates[i]).push(element.title);
}
});
var upcomingData = [];
for (const entry of myMap.entries()) {
var obj = {};
obj["date"] = entry[0];
obj["title"] = entry[1];
upcomingData.push(obj);
}
console.log(upcomingData);
You may
traverse your source array with Array.prototype.reduce() building up the Map where trimmed portion of your date string is used as a key and the object of desired format as a value
extract Map values, using Map.prototype.values() into resulting array
Following is a quick live demo:
const src = [{"data":[{"id":25,"title":"Spotify","name":"Family","service_id":1,"repetition":"Monthly","price":"79000","upcoming_date":["2020-08-07T13:35:44.606Z"]},{"id":26,"title":"Netflix","name":"Mobile","service_id":2,"repetition":"Monthly","price":"49000","upcoming_date":["2020-08-18T13:35:44.600Z","2020-08-07T13:35:44.606Z"]},{"id":27,"title":"iTunes","name":"Weekly Special","service_id":3,"repetition":"Weekly","price":"22000","upcoming_date":["2020-08-07T13:35:44.606Z","2020-08-14T13:35:44.606Z","2020-08-21T13:35:44.606Z","2020-08-28T13:35:44.606Z"]}],"status":"success"}],
result = [...src[0].data
.reduce((r,{upcoming_date, title}) => (
upcoming_date.forEach((s,_,__,date=s.slice(0,10)) =>
r.set(
date,
{date, title: [...(r.get(date)?.title||[]), title]}
)),r),
new Map())
.values()
]
console.log(result)
.as-console-wrapper{min-height:100%;}

React Native Converting JSON objects to array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I fetch some data from the server and the data response comes in this form
[
{
"_id": "5dcb1495daa062304c60c7b0",
"weightTracking": 97,
"weightTrackingDate": "Nov 12"
},
{
"_id": "5dcb14eadaa062304c60c7b1",
"weightTracking": 96,
"weightTrackingDate": "Nov 13"
},
{
"_id": "5dcb161ddaa062304c60c7b2",
"weightTracking": 95,
"weightTrackingDate": "Nov 14"
},
{
"_id": "5dcb1c6cdaa062304c60c7b3",
"weightTracking": 94,
"weightTrackingDate": "Nov 15"
},
]
I want to be able to use this data in my app like that
data={{
labels: ['Nov 12', 'Nov 13', 'Nov 14', 'Nov 15'],
datasets: [
{
data: [
97,
96,
95,
94,
],
},
],
}}
Like [weightTracking] , [weightTrackingDate] in Javascript or react-native
how can I do that? is it possible to do that?
// assuming that data fetched from the server is inside the variable called 'response'
const response = [
{
"_id": "5dcb1495daa062304c60c7b0",
"weightTracking": 97,
"weightTrackingDate": "Nov 12"
},
{
"_id": "5dcb14eadaa062304c60c7b1",
"weightTracking": 96,
"weightTrackingDate": "Nov 13"
},
{
"_id": "5dcb161ddaa062304c60c7b2",
"weightTracking": 95,
"weightTrackingDate": "Nov 14"
},
{
"_id": "5dcb1c6cdaa062304c60c7b3",
"weightTracking": 94,
"weightTrackingDate": "Nov 15"
},
]
const labels = [];
const datasets = [];
response.forEach(item => {
labels.push(item.weightTrackingDate)
datasets.push(item.weightTracking)
})
const data = {
labels: labels,
datasets: [{
data: datasets,
}]
}
Edit: instead of a straightforward answer, I'll add some comments too:
As #byxor stated, it's not at all related to React Native. It's a simple JavaScript task. React Native uses JavaScript but don't get those two confused. Arrays, objects, loops, etc are a feature of the language, not the framework.
You could also use a for() loop for this, instead of using forEach, but it's totally up to you. It mostly comes down to code readability.
This should get you the data in the format you specified
let originalArray = <Your array>;
let data = originalArray.reduce((newObj, currentElement) => {
newObj.labels.push(currentElement.weightTrackingDate);
newObj.datasets[0].data.push(currenElement.weightTracking);
return newObj;
}, { labels: [], datasets: [{data: []}] });
You can use the below code to achieve this:
let arr = [
{
"_id": "5dcb1495daa062304c60c7b0",
"weightTracking": 97,
"weightTrackingDate": "Nov 12"
},
{
"_id": "5dcb14eadaa062304c60c7b1",
"weightTracking": 96,
"weightTrackingDate": "Nov 13"
},
{
"_id": "5dcb161ddaa062304c60c7b2",
"weightTracking": 95,
"weightTrackingDate": "Nov 14"
},
{
"_id": "5dcb1c6cdaa062304c60c7b3",
"weightTracking": 94,
"weightTrackingDate": "Nov 15"
},
];
console.log(arr);
let outarr = [];
let labeles = [];
let dataset = [];
arr.forEach( e => {
labeles.push(e.weightTracking);
dataset.push(e.weightTrackingDate);
})
console.log("----------------------");
console.log(labeles);
console.log(dataset);
let data={};
data.labels = labeles;
data.datasets = {}
data.datasets.data = dataset;
console.log(data);

How to print words from object to specified position in javascript

I have object in javascript and keys of the object are words of my paragraph how to print it in paragraph.Value(key:value) holds its position.
Tried using for loop to fetch didnt work for me
var userdata= {
"\"Ten": [
0
],
"blue": [
1
],
"links\"": [
2
],
"have": [
3
],
"defined": [
4
],
"web": [
5,
36,
65
],
"search": [
6,
32,
37,
70,
90,
108,
126
],
"results": [
7,
33,
38,
71,
82,
99,
119
],
"for": [
8,
80
],
"the": [
9,
28,
56,
61,
69,
95,
105
],
"last": [
10
],
"fifteen": [
11
],
"years": [
12
],
"--": [
13
],
"snippets": [
14
],
"of": [
15,
30,
63,
97,
107,
125
],
"text": [
16
],
"combined": [
17
],
"with": [
18,
60
],
"document": [
19
],
"titles": [
20
],
"and": [
21,
46,
52,
85
],
"URLs.": [
22
],
"In": [
23
],
"this": [
24
],
"paper,": [
25
],
"we": [
26,
111,
114
],
"establish": [
27
],
"notion": [
29
],
"enhanced": [
31,
81,
98,
118
],
"that": [
34,
54,
75,
113
],
"extend": [
35
],
"to": [
39,
58,
103,
120
],
"include": [
40
],
"multimedia": [
41
],
"objects": [
42
],
"such": [
43
],
"as": [
44
],
"images": [
45
],
"video,": [
47
],
"intent-specific": [
48
],
"key": [
49
],
"value": [
50
],
"pairs,": [
51
],
"elements": [
53
],
"allow": [
55
],
"user": [
57
],
"interact": [
59
],
"contents": [
62
],
"a": [
64,
78,
122
],
"page": [
66
],
"directly": [
67
],
"from": [
68
],
"page.": [
72
],
"We": [
73,
92
],
"show": [
74,
112
],
"users": [
76,
102
],
"express": [
77
],
"preference": [
79
],
"both": [
83
],
"explicitly,": [
84
],
"when": [
86
],
"observed": [
87
],
"in": [
88,
100
],
"their": [
89
],
"behavior.": [
91
],
"also": [
93
],
"demonstrate": [
94
],
"effectiveness": [
96
],
"helping": [
101
],
"assess": [
104
],
"relevance": [
106
],
"results.": [
109
],
"Lastly,": [
110
],
"can": [
115
],
"efficiently": [
116
],
"generate": [
117
],
"cover": [
121
],
"significant": [
123
],
"fraction": [
124
],
"result": [
127
],
"pages.": [
128
]
};
"Ten blue links" have defined web search results for the last fifteen years -- snippets of text combined with document titles and URLs. In this paper, we establish the notion of enhanced search results that extend web search results to include multimedia objects such as images and video, intent-specific key value pairs, and elements that allow the user to interact with the contents of a web page directly from the search results page. We show that users express a preference for enhanced results both explicitly, and when observed in their search behavior. We also demonstrate the effectiveness of enhanced results in helping users to assess the relevance of search results. Lastly, we show that we can efficiently generate enhanced results to cover a significant fraction of search result pages.
Convert the object to word/indexes pair with Object.entries(). Iterate the entries using Array.reduce(). Inside the reduce, iterate the indexes with Array.forEach(), and assign each word to its index in the accumulator (r). Join the the array of words with a space.
const userdata = {"\"Ten":[0],"blue":[1],"links\"":[2],"have":[3],"defined":[4],"web":[5,36,65],"search":[6,32,37,70,90,108,126],"results":[7,33,38,71,82,99,119],"for":[8,80],"the":[9,28,56,61,69,95,105],"last":[10],"fifteen":[11],"years":[12],"--":[13],"snippets":[14],"of":[15,30,63,97,107,125],"text":[16],"combined":[17],"with":[18,60],"document":[19],"titles":[20],"and":[21,46,52,85],"URLs.":[22],"In":[23],"this":[24],"paper,":[25],"we":[26,111,114],"establish":[27],"notion":[29],"enhanced":[31,81,98,118],"that":[34,54,75,113],"extend":[35],"to":[39,58,103,120],"include":[40],"multimedia":[41],"objects":[42],"such":[43],"as":[44],"images":[45],"video,":[47],"intent-specific":[48],"key":[49],"value":[50],"pairs,":[51],"elements":[53],"allow":[55],"user":[57],"interact":[59],"contents":[62],"a":[64,78,122],"page":[66],"directly":[67],"from":[68],"page.":[72],"We":[73,92],"show":[74,112],"users":[76,102],"express":[77],"preference":[79],"both":[83],"explicitly,":[84],"when":[86],"observed":[87],"in":[88,100],"their":[89],"behavior.":[91],"also":[93],"demonstrate":[94],"effectiveness":[96],"helping":[101],"assess":[104],"relevance":[106],"results.":[109],"Lastly,":[110],"can":[115],"efficiently":[116],"generate":[117],"cover":[121],"significant":[123],"fraction":[124],"result":[127],"pages.":[128]};
const result = Object.entries(userdata)
.reduce((r, [word, indexes]) => {
indexes.forEach(index => r[index] = word);
return r;
}, [])
.join(' ');
console.log(result);
You can loop through that object and
get the key name (word)
use the provided positions (index) from userdata[word]
define in a result array the index and word to use, such as arrResult[index] = word.
And then, join that array in a string using ' ' as delimiter
In example :
var userdata = {"\"Ten":[0],"blue":[1],"links\"":[2],"have":[3],"defined":[4],"web":[5,36,65],"search":[6,32,37,70,90,108,126],"results":[7,33,38,71,82,99,119],"for":[8,80],"the":[9,28,56,61,69,95,105],"last":[10],"fifteen":[11],"years":[12],"--":[13],"snippets":[14],"of":[15,30,63,97,107,125],"text":[16],"combined":[17],"with":[18,60],"document":[19],"titles":[20],"and":[21,46,52,85],"URLs.":[22],"In":[23],"this":[24],"paper,":[25],"we":[26,111,114],"establish":[27],"notion":[29],"enhanced":[31,81,98,118],"that":[34,54,75,113],"extend":[35],"to":[39,58,103,120],"include":[40],"multimedia":[41],"objects":[42],"such":[43],"as":[44],"images":[45],"video,":[47],"intent-specific":[48],"key":[49],"value":[50],"pairs,":[51],"elements":[53],"allow":[55],"user":[57],"interact":[59],"contents":[62],"a":[64,78,122],"page":[66],"directly":[67],"from":[68],"page.":[72],"We":[73,92],"show":[74,112],"users":[76,102],"express":[77],"preference":[79],"both":[83],"explicitly,":[84],"when":[86],"observed":[87],"in":[88,100],"their":[89],"behavior.":[91],"also":[93],"demonstrate":[94],"effectiveness":[96],"helping":[101],"assess":[104],"relevance":[106],"results.":[109],"Lastly,":[110],"can":[115],"efficiently":[116],"generate":[117],"cover":[121],"significant":[123],"fraction":[124],"result":[127],"pages.":[128]};
let arrResult = [];
for (let word in userdata)
{
userdata[word].forEach((i) =>
{
arrResult[i] = word;
});
}
let result = arrResult.join(' ');
console.log(result);
In your case, your data is the property name itself, so, the easiest way is to get that names with:
var foo = Object.getOwnPropertyNames(userdata);
That function returns you all the property names of the object in an array, so you simply join it:
foo.join(" ");
Hope it suits for you.
EDIT
The above code is not a functional solution in this case, didn't consider the words' index. So the correct way to aproach the solution whould be something like Cid's answer (https://stackoverflow.com/a/55474582/9925983):
const userdata = {"\"Ten":[0],"blue":[1],"links\"":[2],"have":[3],"defined":[4],"web":[5,36,65],"search":[6,32,37,70,90,108,126],"results":[7,33,38,71,82,99,119],"for":[8,80],"the":[9,28,56,61,69,95,105],"last":[10],"fifteen":[11],"years":[12],"--":[13],"snippets":[14],"of":[15,30,63,97,107,125],"text":[16],"combined":[17],"with":[18,60],"document":[19],"titles":[20],"and":[21,46,52,85],"URLs.":[22],"In":[23],"this":[24],"paper,":[25],"we":[26,111,114],"establish":[27],"notion":[29],"enhanced":[31,81,98,118],"that":[34,54,75,113],"extend":[35],"to":[39,58,103,120],"include":[40],"multimedia":[41],"objects":[42],"such":[43],"as":[44],"images":[45],"video,":[47],"intent-specific":[48],"key":[49],"value":[50],"pairs,":[51],"elements":[53],"allow":[55],"user":[57],"interact":[59],"contents":[62],"a":[64,78,122],"page":[66],"directly":[67],"from":[68],"page.":[72],"We":[73,92],"show":[74,112],"users":[76,102],"express":[77],"preference":[79],"both":[83],"explicitly,":[84],"when":[86],"observed":[87],"in":[88,100],"their":[89],"behavior.":[91],"also":[93],"demonstrate":[94],"effectiveness":[96],"helping":[101],"assess":[104],"relevance":[106],"results.":[109],"Lastly,":[110],"can":[115],"efficiently":[116],"generate":[117],"cover":[121],"significant":[123],"fraction":[124],"result":[127],"pages.":[128]};
let words = [];
Object.getOwnPropertyNames(userdata).forEach(propertyName =>
userdata[propertyName].forEach(value => words[value] = propertyName)
);
const text = words.join(' ');
console.log(text);
His answer still being more readable and efficient in my opinion.

first object of array not being passed into initialValue parameter in reduce()

This is my code:
var deliveries = [
{
"id": 1,
"destination": 'Oakland',
"orderPrice": 75,
"rushDelivery": true,
"rushDeliveryFee": 12.75,
"orderDate": "4 April 2016"
},
{
"id": 2,
"destination": 'San Jose',
"orderPrice": 62.75,
"orderDate": "5 April 2016"
},
{
"id": 3,
"destination": 'San Francisco',
"orderPrice": 15.00,
"rushDelivery": true,
"rushDeliveryFee": 50.75,
"orderDate": "10 April 2016"
},
{
"id": 4,
"destination": 'San Francisco',
"orderPrice": 25,
"orderDate": "4/11/2016"
},
{
"id": 5,
"destination": 'San Francisco',
"orderPrice": 90,
"rushDelivery": true,
"rushDeliveryFee": 30,
"orderDate": "April 12, 2015"
},
{
"id": 6,
"destination": 'Berkeley',
"orderPrice": 45,
"orderDate": "4/01/2015"
},
{
"id": 7,
"destination": 'Berkeley',
"orderPrice": 62.16,
"orderDate": "12 April 2016"
}
];
var orderPrices = deliveries.reduce(function(prev, current) {
return prev.orderPrice + current.orderPrice
})
console.log(orderPrices);
When I console.log prev.orderPrice in the first iteration of reduce() it prints undefined, but from what I understand, if you give no second argument(the initialValue) to reduce(), it simply defaults to the first element of the array to which you apply the function to. I would expect the first object of the array to be printed. In fact, if we try this with another simpler array like var arr = [1,2,3,4,5], prev prints 1 in the first iteration.
Why is this happening?
The elements in array are reduced 1 by 1 from left to right. Thus, from the second iteration, the prev argument is the current total value already:
var orderPrices = deliveries.reduce(function (prev, current) {
if (prev.orderPrice)
{
return prev.orderPrice + current.orderPrice;
}
return prev + current.orderPrice;
});
console.log(orderPrices);

Json structure with Javascript Mapping

Is any tool or online editor available so that it specify how to access a json element.For example if i provide json as input ,then we should get an output which will specify each item how can we access through javascript
Example
Assume Input is
var myList={ "vehicleList": { "Vehicle": [ { "vehicleId": 88, "vehicleName": "veh1", "totalEvents": 10, "medium": 2, "Severe": 2, "Category": [ { "AlertId": 1001, "AlertName": "Overspeed", "Alertcount": 10 }, { "AlertId": 1002, "AlertName": "Sudden acceleration", "Alertcount": 40 } ] }, { "vehicleId": 87, "vehicleName": "veh2", "totalEvents": 11, "medium": 4, "Severe": 7, "Category": [ { "AlertId": 1003, "AlertName": "Overspeed", "Alertcount": 30}, { "AlertId": 1004, "AlertName": "Drunk", "Alertcount": 10 } ] }, { "vehicleId": 87, "vehicleName": "veh3", "totalEvents": 10, "medium": 2, "Severe": 2, "Category": [ { "AlertId": 1007, "AlertName": "Overspeed", "Alertcount": 10 }, { "AlertId": 1008, "AlertName": "Overspeed", "Alertcount": 77 } ] }, { "vehicleId": 86, "vehicleName": "veh4", "totalEvents": 11, "medium": 4, "Severe": 5, "Category": [ { "AlertId": 1009, "AlertName": "Overspeed", "Alertcount": 17 }, { "AlertId": 1010, "AlertName": "HighSpeed", "Alertcount": 10 } ] } ] } };
Output should be a structure,which will specify like
myList.vehicleList.Vehicle[3].Severe;
It seems like you looking backward means providing the value you need what will be the expression to get the value. I don't have a solution for that.
But I would like to suggest json is very easy to read, may be you are having trouble due to long chunk of string. Try this website(editor) http://jsonlint.com/ this will validate your json and give you in more readable form. Hope this will help you in one or other way.

Categories

Resources