I am new to javascript. How do I iterate a JSON result that has convert into javascript object?
const url = 'https://api.mybitx.com/api/1/tickers?pair=XBTMYR';
fetch(url)
.then(res => res.json())
//.then(json => console.log(json))
.then(function(data) {
let bp = data.tickers
console.log(bp.timestamp)
})
the object results are
[ { timestamp: 1500349843208,
bid: '9762.00',
ask: '9780.00',
last_trade: '9760.00',
rolling_24_hour_volume: '325.277285',
pair: 'XBTMYR' } ]
I just want to print out the "timestamp" key. Thanks.
Put key and then the object.
console.log(bp[0].timestamp)
Your result is an array, as such you can iterate it by index or by using for or .forEach.
for(var i=0; i<bp.length;i++) {
var element= bp[i];
}
Each element in your array is an object. To access the timestamp of that element use ["timestamp"] or .timestamp
for(var i=0; i< bp.length; i++) {
var element = bp[i];
var timestamp = element.timestamp;
var ts= element["timestamp"];
}
To get the first time stamp use simply use b[0].timestamp.
Related
I have an array, each subarray of which contains different positions in different order:
[
["apple(2)", "banana(5)"],
["peach(3)", "banana(1)"],
["apple(1)"]
]
I need to sort it on JavaScript (ES6) and i expect to get an array like this:
[
["apple(2)", "banana(5)", "peach(0)"],
["apple(0)", "banana(1)", "peach(3)"],
["apple(1)", "banana(0)", "peach(0)"]
]
Order of each subarray should be the same. If subarray don't have some position, i need to add it with 0 value. Can i using something like map() or sort() function or need to compare it manually?
Here is functional programming approach, using a Map and reduce:
const data = [['apple(2)', 'banana(5)'],['peach(3)', 'banana(1)'],['apple(1)'],];
// Create a Map with default values for each name, i.e. with "(0)":
let names = new Map(data.flat().map(item => [item.replace(/\d+/, ""), item.replace(/\d+/, "0")]));
let result = data.map(row =>
[...row.reduce((map, item) =>
map.set(item.replace(/\d+/, ""), item), // Overwrite default
new Map(names) // Start with clone of original Map
).values()]
);
console.log(result);
You have to loop over to get the keys used. You then have to loop over a second time to get the fill in the missing keys. There are many ways of doing it, this is one.
var data = [
["apple(2)", "banana(5)"],
["peach(3)", "banana(1)"],
["apple(1)"]
];
// match string and number
var re = /([^(]+)\((\d+)\)/;
// Loop over and find all of the keys
var grouped = data.reduce((info, subset, index) => {
subset.forEach(item => {
// find the key and count
var parts = item.match(re);
// have we seen this key?
if (!info[parts[1]]) {
// if not create an array
info[parts[1]] = Array(data.length).fill(0);
}
// set the key index with the count
info[parts[1]][index] = parts[2];
})
return info;
}, {});
// loop over the groups and fill in the set
Object.entries(grouped).forEach(([key, counts], colIndex) => {
counts
.forEach((cnt, rowIndex) => {
data[rowIndex][colIndex] = `${key}(${cnt})`;
})
});
console.log(data);
First get the unique words. Then traverse array of arrays to check if the word is present or not. If it is not present then make the word according to your condition and if present then put the original word to the tmp array. At last sort it for each iteration. By the way, I used regex replace method to get the word.
const data = [
['apple(2)', 'banana(5)'],
['peach(3)', 'banana(1)'],
['apple(1)'],
];
const words = [...new Set(data.flat().map((x) => x.replace(/[^a-z]/gi, '')))];
const ret = data.map((x) => {
const tmp = [];
const newX = x.map((y) => y.replace(/[^a-z]/gi, ''));
for (let i = 0, l = words.length; i < l; i += 1) {
if (newX.includes(words[i])) tmp.push(x.shift());
else tmp.push(`${words[i]}(0)`);
}
return tmp.sort();
});
console.log(ret);
What is Wrong in below code? getting last index value.in all JSON Object
let arr = ['apple','banana','cherry'];
let dataJson=[];
let json={}
console.log('lent',arr.length);
for(var i = 0; i<arr.length;i++) {
json.name=arr[i];
json.type="fruit";
dataJson.push(json);
}
You are passing the object reference within the array. In the last iteration the object will have cherry which is reflected in all objects passed within the array. Instead, use Object.assign to create new object.
let arr = ['apple','banana','cherry'];
let dataJson=[];
let json={}
for(var i = 0; i<arr.length;i++) {
json.name=arr[i];
json.type="fruit";
dataJson.push(Object.assign({}, json));
}
console.log(dataJson);
You can achieve the same functionality using reduce.
let fruits = ['apple','banana','cherry'];
const output = fruits.reduce((a, fruit) => {
a.push({"name": fruit, type: "fruit"});
return a;
}, []);
console.log(output);
I would use map to do it
const arr = ['apple','banana','cherry']
const dataJson = arr.map(fruitName => ({name: fruitName, type: 'fruit'}))
console.log(dataJson)
It looks like you're trying to convert your array of string fruit names in to a JavaScript Object. Currently, your code is always overwritting the name property with every iteration. I would suggest pushing an object in every iteration instead.
let arr = ['apple','banana','cherry'];
let dataJson = [];
console.log('lent',arr.length);
for(var i = 0; i <arr.length; i++) {
dataJson.push({name: arr[i], type: 'fruit'} )
}
console.log(dataJson);
// Modern way of doing it with Array.map
const data = ['apple','banana','cherry'].map( d => ( { name: d, type: 'fruit' } ) );
console.log(data);
In other news, JSON is a string. You're working with a JavaScript Object.
I have a data response of form:
claim_amount_arr: [218691.44]
claim_approval_status: ["In Process"]
percentages_claim: [1]
percentages_claim_amount: [1]
total_claim_arr: [2]
_id: 0
__proto__: Object
I want to convert it to array so as to map it into table further in a component. Since it does not have a key, I am not able to access it's key value pair for mapping.
I tried the following approach but then it eliminates all the key from the array:
const summary_props = this.props.summary
//console.log(summary_props); //this console gives me data as shown in image above
const sortedvalue = Object.keys(summary_props).map(key => {
return summary_props[key];
});
console.log(sortedvalue);
output of this console:
Please help.
class ClaimInformation()
{
constructor(data,index)
{
this.claim_amount = data.claim_amount_arr[index];
this.claim_approval_status = data.claim_approval_status[index];
this.percentage_claim = data.percentage_claim[index];
this.percentages_claim_amount = data.percentages_claim_amount[index];
this.total_claim = data.total_claim_arr[index];
}
}
var claims = [];
for(let i = 0; i < response.claim_amount_arr.length; i++){
claims.push(new ClaimInformation(response,i));
}
Try Object.entries().
In short, it can transform an object into an array.
Edit: More specific here
Object.entries(formData).map(([key, value]) => {
//Now you can access both the key and their value
})
I have the following json object:
[{"i_value":"1","i_value_2":"1"},
{"i_value":"24","i_value_2":"24"}]
Then I have the following loop:
let setData = [];
for (let i = 0; i < response.data.length; i++) {
if ('access key name' === 'i_value') {
setData.push(response.data[i].i_value)
}
}
setData = setData.map(Number);
console.log(setData);
I only want to populate the new setData array when the key name === i_value not i_value_2
I tried the following:
let setData = [];
let keys = Object.keys(response.data);
for (let i = 0; i < response.data.length; i++) {
if (keys[i] === 'i_value') {
setData.push(response.data[i].i_value)
}
}
setData = setData.map(Number);
console.log(setData);
But this doesn't work. Any thoughts on this?
Just take the original data and .map, extracting the i_value property:
const input = [{"i_value":"1","i_value_2":"1"},
{"i_value":"24","i_value_2":"24"}];
console.log(
input.map(({ i_value }) => Number(i_value))
);
Also note that there's no such thing as a JSON object. If you have an object, you just have an object; JSON format is a format for strings that can be transformed into objects via JSON.parse.
You can use map() to create a new array with the results of calling a provided function on every element in the calling array in the following way:
var response = {}
response.data = [{"i_value":"1","i_value_2":"1"},
{"i_value":"24","i_value_2":"24"}]
let setData = response.data.map(o => Number(o.i_value));
console.log(setData);
This is the approach I am trying to realize in JavaScript to append the "path" key to the strings in response.data.
var arraySujets = [];
arraySujets[path] = [];
for (let i in response.data) {
arraySujets[i][path] = response.data[i];
}
My response.data ist just a simple array of strings:
array:2 [
0 => "/example/path1"
1 => "/example/path2"
]
However the above code returns a
ReferenceError: path is not defined
Several solutions can be applied here.
assuming,
data = ["/example/path1", "/example/path2" ]
Standart for-loop
arraySujets = [];
for(var i=0; i<response.data.length; i++) {
arraySujets[i] = {path: response.data[i]}
}
Foreach with arrow functions.
response.data.forEach(e => arraySujets.push({path: e}))
/*
*response.data.forEach(function(e) {
* arraySujets.push({path: e})
*})
*/
Just use
var arraySujets = {}; // This must be an object, not an array
arraySujets["path"] = [];
That will access the path key in the object arraySujets
You may want to keep the responses in some objects.
You can try something like this:
var arraySujets = response.data.map(function(resp) {
return {
path: resp
}
})