Props name getting converted as object key - javascript

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

Related

How to restart the numeration of the keys in a object?

What is the problem :
this are my data stored in this.state.jsondata :
{
label{0:1,1:1}
prediction{0:0,1:1}
text{0:"abc",1:"def"}
}
This comes front JSON.stringify(this.state.jsondata) :
{"label":{"1":0,"2":0,"3":0,"4":0},"text":{"1":"aa","2":"bb,"3":"cc","4":"dd"},"prediction":{"1":2,"2":2,"3":2,"4":2}}
when I delete one element using this code :
removeData = (keyToRemove) => {
// create a deep copy of the object
const clonedJsonData = JSON.parse(JSON.stringify(this.state.jsondata))
// now mutate this cloned object directly
Object.keys(clonedJsonData).forEach(key => delete clonedJsonData[key][keyToRemove])
// set the state
this.state.jsondata = clonedJsonData
this.state.jsondata becomes :
{
label{1:1}
prediction{1:1}
text{1:"def"}
}
instead of starting back to 0 like :
{
label{0:1}
prediction{0:1}
text{0:"def"}
}
So basically I want to set the key back to "0, 1, 2, 3.."
What have I tried :
I tried to iterate through my data but there is something wrong in it with the way I loop through it :
removeData = (keyToRemove) => {
// create a deep copy of the object
const clonedJsonData = JSON.parse(JSON.stringify(this.state.jsondata))
// now mutate this cloned object directly
Object.keys(clonedJsonData).forEach(key => delete clonedJsonData[key][keyToRemove])
// reset keys value
let i = 0
Object.keys(clonedJsonData).forEach(function(key) {
Object.keys(clonedJsonData[key]).forEach(function(k) {
var newkey = i++;
clonedJsonData[key][k] = clonedJsonData[key][k];
delete clonedJsonData[key][k];
})
})
// set the state
this.state.jsondata = clonedJsonData
}
What is the expected output ?
The expected output is :
{
label{0:1}
prediction{0:1}
text{0:"def"}
}
If your key basically represents the index of the value, why not using an array?
{ label: [1,1], prediction: [0,1], text: ["abc","def"] }
If you now delete the first entry in each array, data.text[0] will be "def" and so on...
Edit:
If you don't want to convert the data, you gotta be carefull, especially if you parse and stringify the whole thing around and then loop over the keys. They don't have to be in the same order afterwards.
Instead of cloning the object, deleting the key you want to remove and then updating all keys, you could also copy the object manually and leaving the key to remove out
var data = {label: {0:0, 1:0}, prediction: {0:0, 1:1}, text: {0:'abc',1:'def'}};
console.log("Original Data");
console.log(data);
removeData = (data, keyToRemove) => {
var ret = {};
Object.keys(data).forEach(key=>{
ret[key] = {};
let idx = 0;
for (let dataIdx = 0; dataIdx < Object.keys(data[key]).length; dataIdx++) {
if (dataIdx.toString() !== keyToRemove) {
ret[key][idx.toString()] = data[key][dataIdx.toString()];
idx++;
}
}
});
return ret;
}
var reducedData = removeData(data,"0");
console.log("Reduced Data");
console.log(reducedData);
Note that I don't loop over the keys, so I don't get the order mixed up.
Note that I also removed the side effects from your original function by handing over the data object as parameter.
So that's how I made it
removeData = (keyToRemove) => {
// create a deep copy of the object
const clonedJsonData = JSON.parse(JSON.stringify(this.state.jsondata))
// now mutate this cloned object directly
Object.keys(clonedJsonData).forEach(key => delete clonedJsonData[key][keyToRemove])
// reset keys value
let i = 0
Object.keys(clonedJsonData).forEach(function eachKey(key) {
i = 0
Object.keys(clonedJsonData[key]).forEach(function eachKey(kkey) {
var newkey = i++;
clonedJsonData[key][newkey] = clonedJsonData[key][kkey];
});
delete clonedJsonData[key][i];
});
// set the state
this.state.jsondata = clonedJsonData
}

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.

Loop through JSON object and generate array based on key name

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

storing key value pairs in an array in javascript

I have 2 arrays namely,
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom","testDesc"];
I want to store the values as a key value pair in another array, something like this:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
Kindly note that the array values are dynamic, so I cannot hardcode them.
Is there a way to do so? I am able to achieve the above said requirement but the length always shows 0. This is the code that I am using:
configdata.Incident_Field.forEach(function (k, i) {
this[k] = ticketarray[i];
}, ticketData);
Other people have explained why your code did not work. I am providing another solution using reduce.
const configdata = ["assignee", "shortDesc"];
const ticketarray = ["Tom", "testDesc"];
let ticketData = configdata.reduce((result, value, index) => {
result[value] = ticketarray[index];
return result;
}, {});
console.log(ticketData);
Output:
{
assignee: "Tom",
shortDesc: "testDesc"
}
The below is not a valid structure in JavaScript:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
What you need is a JavaScript object. The best you can do is:
Make sure both the array lengths are same.
Associate the key and value by creating a new object.
Use Object.keys(obj).length to determine the length.
Start with the following code:
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom", "testDesc"];
if (configdata.length == ticketarray.length) {
var obj = {};
for (var i = 0; i < configdata.length; i++)
obj[configdata[i]] = ticketarray[i];
}
console.log("Final Object");
console.log(obj);
console.log("Object's Length: " + Object.keys(obj).length);
The above will give you an object of what you liked, a single variable with all the values:
{
"assignee": "Tom",
"shortDesc": "testDesc"
}

How to get a number value within an object that is in an object

My code:
rbx.getPlayers(539310, 1).promise.then(players => {
console.log(players)
for (var list in players.players) {
console.log(list)
var key = Object.Key(list)
console.log(Key)
}
})
What it outputs:
{ total: 9,
players:
{ AgentJay400: 65910635,
MatthewHAndreas: 49787909,
coolguysocoolroblox: 165524669,
CAMPER5155: 45422370,
Mavnkei: 69082588,
kaankerem123: 92305180,
egehan432: 120777218,
panpanaber54: 31962303,
IXTactical_CactusXI: 17451343 } }
AgentJay400
MatthewHAndreas
coolguysocoolroblox
CAMPER5155
Mavnkei
kaankerem123
egehan432
panpanaber54
IXTactical_CactusXI
Problem:
I need the number values of each user (So {AgentJay4000: 65910635} I would want the 65910635) Node.js does not seem to have Object.keys so... I have no clue how to get the number...
Node should definitely have Object.keys. If your version doesn't you should update node. When you call Object.keys you get an array in return, so you can do awesome array things like map, reduce, forEach:
Object.keys(players.players).forEach(function(key) {
console.log(key, players.players[key])
})
If you just want the number values, then map it:
Object.keys(players.players).map(function(key) {
return players.players[key]
})
Now you have an array of the numbers only.
Try like this.You can access your object value using . operator.
Suppose you have an object:
var obj={
key1:value1,
key2:value2
}
Then access values like obj.key1 or obj['key1'].
to get all the values.Use Object.values(obj);
var obj = { total: 9,
players:
{ AgentJay400: 65910635,
MatthewHAndreas: 49787909,
coolguysocoolroblox: 165524669,
CAMPER5155: 45422370,
Mavnkei: 69082588,
kaankerem123: 92305180,
egehan432: 120777218,
panpanaber54: 31962303,
IXTactical_CactusXI: 17451343 } };
var players = obj.players;
var number_values = Object.values(players);
console.log(number_values );
You can output the keys and their associated numbers by doing the following:
rbx.getPlayers(539310, 1).promise.then(players => {
console.log(players)
for (var key in players.players) {
console.log(key, ':', players.players[key])
}
})
To demonstrate how Object.keys works an alternative method of accessing the players - this does the same as the above.
rbx.getPlayers(539310, 1).promise.then(players => {
var keys = Object.keys(players.players);
for (var i = 0; i < keys.length; i++) {
let key = keys[i];
let player = players.players[key];
console.log(key, ':', players.players[key])
}
});
The mistakes you made in your attempt were you were attempting to access Object.key which was a typo for Object.keys and attempting to obtain a list of keys from a string (as a loop such as for(var key in obj) will set key to each key in obj and all object keys are strings).

Categories

Resources