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);
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.
I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.
var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();
This works fine, but I don't want to mention any index number. I want all elements of my array to be an object. How do I declare or initialize it?
var sample = new Array();
sample[] = new Object();
I tried the above code but it doesn't work. How do I initialize an array of objects without using an index number?
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
To do this n times use a for loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
Depending on what you mean by declaring, you can try using object literals in an array literal:
var sample = [{}, {}, {} /*, ... */];
EDIT: If your goal is an array whose undefined items are empty object literals by default, you can write a small utility function:
function getDefaultObjectAt(array, index)
{
return array[index] = array[index] || {};
}
Then use it like this:
var sample = [];
var obj = getDefaultObjectAt(sample, 0); // {} returned and stored at index 0.
Or even:
getDefaultObjectAt(sample, 1).prop = "val"; // { prop: "val" } stored at index 1.
Of course, direct assignment to the return value of getDefaultObjectAt() will not work, so you cannot write:
getDefaultObjectAt(sample, 2) = { prop: "val" };
You can use fill().
let arr = new Array(5).fill('lol');
let arr2 = new Array(5).fill({ test: 'a' });
// or if you want different objects
let arr3 = new Array(5).fill().map((_, i) => ({ id: i }));
Will create an array of 5 items. Then you can use forEach for example.
arr.forEach(str => console.log(str));
Note that when doing new Array(5) it's just an object with length 5 and the array is empty. When you use fill() you fill each individual spot with whatever you want.
After seeing how you responded in the comments. It seems like it would be best to use push as others have suggested. This way you don't need to know the indices, but you can still add to the array.
var arr = [];
function funcInJsFile() {
// Do Stuff
var obj = {x: 54, y: 10};
arr.push(obj);
}
In this case, every time you use that function, it will push a new object into the array.
You don't really need to create blank Objects ever. You can't do anything with them. Just add your working objects to the sample as needed. Use push as Daniel Imms suggested, and use literals as Frédéric Hamidi suggested. You seem to want to program Javascript like C.
var samples = []; /* If you have no data to put in yet. */
/* Later, probably in a callback method with computed data */
/* replacing the constants. */
samples.push(new Sample(1, 2, 3)); /* Assuming Sample is an object. */
/* or */
samples.push({id: 23, chemical: "NO2", ppm: 1.4}); /* Object literal. */
I believe using new Array(10) creates an array with 10 undefined elements.
You can instantiate an array of "object type" in one line like this (just replace new Object() with your object):
var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });
Well array.length should do the trick or not? something like, i mean you don't need to know the index range if you just read it..
var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.
IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:
var arrayContainingObjects = [];
for (;;){
try{
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
}
catch(err){
break;
}
It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.
//making array of book object
var books = [];
var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
books.push(new_book);
new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
books.push(new_book);
console.log(books[0].id);
console.log(books[0].name);
console.log(books[0].category);
console.log(books[0].price);
// also we have array of albums
var albums = []
var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
albums.push(new_album);
new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);
console.log(my_albums[0].name);
console.log(my_albums[1].name);
This Example Works with me.
Snapshot for the Output on Browser Console
Try this-
var arr = [];
arr.push({});
const sample = [];
list.forEach(element => {
const item = {} as { name: string, description: string };
item.name= element.name;
item.description= element.description;
sample.push(item);
});
return sample;
Anyone try this.. and suggest something.
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
you can use it
var x = 100;
var sample = [];
for(let i=0; i<x ;i++){
sample.push({})
OR
sample.push(new Object())
}
Using forEach we can store data in case we have already data we want to do some business login on data.
var sample = new Array();
var x = 10;
var sample = [1,2,3,4,5,6,7,8,9];
var data = [];
sample.forEach(function(item){
data.push(item);
})
document.write(data);
Example by using simple for loop
var data = [];
for(var i = 0 ; i < 10 ; i++){
data.push(i);
}
document.write(data);
If you want all elements inside an array to be objects, you can use of JavaScript Proxy to apply a validation on objects before you insert them in an array. It's quite simple,
const arr = new Proxy(new Array(), {
set(target, key, value) {
if ((value !== null && typeof value === 'object') || key === 'length') {
return Reflect.set(...arguments);
} else {
throw new Error('Only objects are allowed');
}
}
});
Now if you try to do something like this:
arr[0] = 'Hello World'; // Error
It will throw an error. However if you insert an object, it will be allowed:
arr[0] = {}; // Allowed
For more details on Proxies please refer to this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
If you are looking for a polyfill implementation you can checkout this link:
https://github.com/GoogleChrome/proxy-polyfill
The below code from my project maybe it good for you
reCalculateDetailSummary(updateMode: boolean) {
var summaryList: any = [];
var list: any;
if (updateMode) { list = this.state.pageParams.data.chargeDefinitionList }
else {
list = this.state.chargeDefinitionList;
}
list.forEach((item: any) => {
if (summaryList == null || summaryList.length == 0) {
var obj = {
chargeClassification: item.classfication,
totalChargeAmount: item.chargeAmount
};
summaryList.push(obj);
} else {
if (summaryList.find((x: any) => x.chargeClassification == item.classfication)) {
summaryList.find((x: any) => x.chargeClassification == item.classfication)
.totalChargeAmount += item.chargeAmount;
}
}
});
if (summaryList != null && summaryList.length != 0) {
summaryList.push({
chargeClassification: 'Total',
totalChargeAmount: summaryList.reduce((a: any, b: any) => a + b).totalChargeAmount
})
}
this.setState({ detailSummaryList: summaryList });
}
var ArrayofObjects = [{}]; //An empty array of objects.