select value from object in javascript - javascript

Hi I am getting dificulties to select value from this dictionary,
my object
[{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
4fd5ee28-835d-42dc-85a6-699a37bc1948: "54",
f45827c8-1b1a-48c3-831b-56dab9bcaf3b: "543"
},
saved: true}]
I need to get cost of 54 somehow.
please help

<script>
var arraylist = [{'id': "063f48d0-1452-4dad-8421-145820ddf0f8",
'storeName': "birr",
'cost': {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
'saved': true}];
var costKey = '4fd5ee28-835d-42dc-85a6-699a37bc1948'
var selectedCost = arraylist[0]['cost'][costKey];
alert(selectedCost);
</script>

Your GUIDs in cost need to be inside quotes.
var obj = [{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
saved: true
}]
document.write(obj[0].cost['4fd5ee28-835d-42dc-85a6-699a37bc1948']);
That outputs the value 54.

Make sure your keys are in quotes. Otherwise to retrieve the value it is simply a matter of accessing it like object[key] as the following code demonstrates.
var stores = [{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
saved: true
}];
var store = stores[0];
var cost = store.cost;
var key = Object.keys(cost)[0];
var value = cost[key];
console.log(value);

Related

How to get only one value in Javascript array of objects using for of and for in statements?

Here is my array of objects, where I want to get specific value.
{ customerName: "Jay", Purchased: "phone", Price: "€200" },
{ customerName: "Leo", Purchased: "car", Price: "€2000" },
{ customerName: "Luk", Purchased: "Xbox", Price: "€400" },
];
in this function I get all values together. But I want specific value in order to show smth like this in console using for of and for in statements. "Dear Jay thank you for purchase of a phone for the price of €200 "
function getValue(){
for(let key of customerData){
for(let value in key){
console.log(key[value]) //I get all values
//console.log(value) // I get all keys
}
}
}
getValue();```
You don't need multiple for loop for this. You can do this using one forEach() loop and template literal like:
var customerData = [{ customerName: "Jay", Purchased: "phone", Price: "€200" },
{ customerName: "Leo", Purchased: "car", Price: "€2000" },
{ customerName: "Luk", Purchased: "Xbox", Price: "€400" },
];
function getValue() {
customerData.forEach(x => {
console.log(`Dear ${x.customerName} thank you for purchase of a ${x.Purchased} for the price of ${x.Price}`)
})
}
getValue();
var customerData = [{ customerName: "Jay", Purchased: "phone", Price: "€200" },
{ customerName: "Leo", Purchased: "car", Price: "€2000" },
{ customerName: "Luk", Purchased: "Xbox", Price: "€400" },
]
function getValue(){
for(let key of customerData){
for(let value in key){
console.log(key[value]) //I get all values
break;
//It Work
}
}
}
getValue();
By passing the object position in the array as a parameter for the function you can get the single object keys
function getValue(data){
for(let key of Object.values(data)){
console.log(key)
}
}
getValue(a[1]);
// Output
Leo car €2000
You need to pass the name of the customer you're looking for and the data you want about them. Then you can use Array.filter() and Array.map()
Then you can put the functions into a template literal to get your result.
let customerData=[{customerName:"Jay",Purchased:"phone",Price:"€200"},{customerName:"Leo",Purchased:"car",Price:"€2000"},{customerName:"Luk",Purchased:"Xbox",Price:"€400"}]
function getValue(name, otherKey) {
return customerData.filter(obj => obj.customerName === name).map(obj => obj[otherKey])[0]
}
console.log(getValue("Jay", "Purchased"))
console.log(getValue("Luk", "Price"))
let str = `Dear Jay thank you for purchase of a ${getValue("Jay", "Purchased")} for the price of ${getValue("Jay", "Price")}`
console.log(str)

How to make an array of objects with different label and value in Reactjs

I am using this.state.student in react to display (name,school,class.etc)..
how i change the "school" display to "college" without replacing the value of "School" in the api..
as i am new to code i tried
'var student = [ {"name", "school", "class"}];'
'student[1] = "college";'
but this just replaces the value. i just want to change the display
of "school" please help
Check my code. I created a function addToArray that will accept a parameter of object then it will add it to the students array. This will give you an output of [{ name: "John Doe", school: "College", class: "A" }]
let students = [];
addToArray = student => {
students.push({
name: student.name,
school: student.school,
class: student.class
});
console.log(students);
};
this.addToArray({
name: "John Doe",
school: "College",
class: "A"
});
Use this to create an array of objects with different key and value pair,
var productArr = [];
productId = 1;
productName = 'Product Name';
productArr.push({ id: productId, name: productName });
Hope it'll work for you. Waiting for your response. Thank you!
You can try this:
var student = [ {"name": "school", "class":"XYZ"}];
student = [...student,{"name":"college","class":"ABC"}]
console.log(student)

Javascript copy no repeat object data taht have same property from array

I have an arrry that has 100 object and it has same property code
Data = [
{yera:"2019", name:"saif", topic:"oil"},
{yera:"2018", name:"abc", topic: "oil"},
{yera:"2018", name:"jorj", topic:"energy"},
{yera:"2017", name:"tom", topic:"gas"},
{yera:"2016",name:"saif",topic:"electricity "},
{yera:"2014", name:"gour",topic:"oil"},
Assuming you want to remove duplicates from the array of objects based on a key of that object, the code below will achieve that.
var data = [
{yera:"2019", name:"saif", topic:"oil"},
{yera:"2018", name:"abc", topic: "oil"},
{yera:"2018", name:"jorj", topic:"energy"},
{yera:"2017", name:"tom", topic:"gas"},
{yera:"2016",name:"saif",topic:"electricity "},
{yera:"2014", name:"gour",topic:"oil"}
]
function getUniqueData(originalData, keyToCheckForUniqueness) {
var store = {};
var output = [];
originalData.forEach(function (ob) {
var val = ob[keyToCheckForUniqueness];
if (!store[val]) {
store[val] = [ob];
} else {
store[val].push(ob);
}
});
// at this point your store contains all the repeating data based on that property value
// console.log(store);
// now emit single values from that store;
// this logic can be based on any criterion, I chose the first element of the array - it may change depending on the order of values in input
Object.keys(store).forEach(function (key) {
var uniqueValArray = store[key];
var uniqueVal = uniqueValArray[0]; // take the first entry
output.push(uniqueVal);
});
return output;
}
getUniqueData(data, "topic");
This will achieve what I think you want to figure out. A word of advice - Don't let people think when you ask them for help. Second, try writing the logic for yourself. Post your non-working solution and ask, where you made a mistake - rather than asking. Given your rep, welcome to SO. Hope you a great learning experience.
Assuming, you want unique values for a given property of the objects, you could map that value and take a Set for getting unique values.
function getUnique(array, key) {
return Array.from(new Set(array.map(({ [key]: v }) => v)));
}
var array = [{ year: "2019", name: "grace", topic: "oil" }, { year: "2018", name: "grace", topic: "oil" }, { year: "2018", name: "jane", topic: "energy" }, { year: "2017", name: "tom", topic: "gas" }, { year: "2016", name: "jane", topic: "electricity" }, { year: "2014", name: "gour", topic: "oil" }];
console.log(getUnique(array, 'year'));
console.log(getUnique(array, 'name'));
console.log(getUnique(array, 'topic'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

JS arrays: how to compare two and create third

It's my first post here :-)
Please, Can you a advice on this:
I have an object and an Array:
activeItems = {
itemId: ["itemid1", "itemid2", "itemid3", "itemid4", "itemid5", "itemid6", "itemid7", "itemid8", "itemid9", "itemid10"],
price: ["10.50", "22.10", "13.40", "11", "1100", "500", "100", "400", "500", "20"]
};
selectItems = ["itemid3", "itemid8", "itemid9"];
In the activeItems object price[0] represents the price for itemId[0].
All the prices are in correct order to represent prices for all item ids.
Now, I would like to create a new object with prices for the selecteItems array.
It should look like this:
newObject = {
itemId: ["itemid3","itemid8","itemid9"],
price: ["13.40", "400", "500"]
};
Basically, I'm looking for a formula that creates new object for selectedItems out of activeItems and adds prices arrays for them.
Thank you in advance!
Use a forEach loop and get the index of items from activeItems.itemId which can be used to get the corresponding price value from activeItems.price.
var activeItems = {
itemId: ["itemid1", "itemid2", "itemid3", "itemid4", "itemid5", "itemid6", "itemid7", "itemid8", "itemid9", "itemid10"],
price: ["10.50","22.10","13.40","11","1100","500","100","400","500","20"]
};
var selectItems = ["itemid3","itemid8","itemid9"];
var itemId = [];
var price = [];
selectItems.forEach(function(item){
var index = activeItems.itemId.indexOf(item);
itemId.push(item);
price.push(activeItems.price[index]);
});
var newObject = {
itemId: itemId,
price : price
};
console.log(newObject);
Maybe this is what you need: Key value arrays:
var myArray = {"itemid3": "13.40", "itemid8": "400", "itemid9": "500"};
And you add new items like this:
myArray = [];
myArray.itemid15 = "300";
Use the array reduce function
var activeItems = {
itemId: ["itemid1", "itemid2", "itemid3", "itemid4", "itemid5", "itemid6", "itemid7", "itemid8", "itemid9", "itemid10"],
price: ["10.50", "22.10", "13.40", "11", "1100", "500", "100", "400", "500", "20"]
};
var selectItems = ["itemid3", "itemid8", "itemid9"];
var newObject = selectItems.reduce(function(acc, curr, index) {
// acc is the object passes as an argument
// curr is current element
// in this case curr will be "itemid3", "itemid8", "itemid9" ..so on
acc.itemId.push(curr);
// in next step get the index of the itemId3 etc from the original array
// use this index to get the value from activeItems .price
acc.price.push(activeItems.price[activeItems.itemId.indexOf(curr)])
return acc;
}, {
itemId: [],
price: []
});
console.log(newObject)

How to get distinct values and sum the total on JSON using JS

How do you get the data from distinct values also sum the total values from the same unique row
Here is the JSON Data result
As you can see they have the same full name. How do you get the distinct value while sum the total priceGross.
The result should be returning
eg. "Khalem Williams" and adding the total priceGross " 1200 + 1200 " = 2400
result return
FullName : "Khalem Williams"
TotalPriceGross: "2400"
I'm getting the distinct values with the code below but I'm wondering how to sum the total priceGross while also getting the distinct values.
var countTotal = [];
$.each(data.aaData.data,function(index, value){
if ($.inArray(value.invoiceToFullName, countTotal)==-1) {
countTotal.push(value.invoiceToFullName);
}
});
I would honestly suggest converting your data to an object with names as keys (unique) and total gross prices as values:
{
"Khalem Williams": 2400,
"John Doe": 2100
}
However, I have included in the snippet below example code for how to convert your data to an array of objects as well. I used a combination of Object.keys, Array#reduce and Array#map.
var data = {
aaData: {
data: [{
invoiceToFullName: "Khalem Williams",
priceGross: 1200
},
{
invoiceToFullName: "Khalem Williams",
priceGross: 1200
},
{
invoiceToFullName: "John Doe",
priceGross: 500
},
{
invoiceToFullName: "John Doe",
priceGross: 1600
},
]
}
}
var map = data.aaData.data.reduce(function(map, invoice) {
var name = invoice.invoiceToFullName
var price = +invoice.priceGross
map[name] = (map[name] || 0) + price
return map
}, {})
console.log(map)
var array = Object.keys(map).map(function(name) {
return {
fullName: name,
totalPriceGross: map[name]
}
})
console.log(array)
Just created my own dummy data resembling yours hope you get the idea, if not you can paste your json and i can adjust my solution, was just lazy to recreate your json.
Your problem seems to be a typical group by field from sql.
Sample data:
var resultsData = [{name: 'sipho', amount: 10}, {name: 'themba', amount: 30}, {name: 'sipho', amount: 60}, {name: 'naidoo', amount: 30}, {name: 'gupta', amount: 70}, {name: 'naidoo', amount: 10}];
Get value of customer(field) you going to group by:
var customers = $.unique(resultsData.map(function(value){return value.name}));
Go through each customer and add to their sum:
var desiredSummary = customers.map(function(customer){
var sum =0;
$.each(test,function(index, value){sum+=(value.name==customer?value.amount:0)});
return {customer: customer, sum: sum}
});
Hope it helps, Happy coding

Categories