Loop through JSON object and generate array based on key name - javascript

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

Related

Getting Last Index Value in JSON

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.

Props name getting converted as object key

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

How to append key values to a simple array of strings?

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

iterate JavaScript object

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.

Get index from jquery array objects

I get this array in my chrome console, using this method $("#gallery_thumbnails .owl-item.active").get();:
Array[5]
0:div.owl-item.active
1:div.owl-item.active.synced
2:div.owl-item.active
3:div.owl-item.active
4:div.owl-item.active
But I want only the array indexs, like this:
How can I get this result?
Iterate over your object array and save keys to new array.
var out = [];
for (key in arrays) {
out.push(key);
}
console.log(out);
Or as suggested by other user, use this method:
var out = [];
for (var i = 0; i < array.length; i++) {
out.push(i);
}
console.log(out);
You could use the map method from jQuery
$.map($("#gallery_thumbnails .owl-item.active").get(), function (val, i) {
return i;
});

Categories

Resources