How to assign values of one array to another array? - javascript

I have got two arrays by name actutalpricesarray and modfiedpricesarray .
var actutalpricesarray =
[
{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
]
var modfiedpricesarray =
[
{"name":"apple","price":20},
{"name":"orange","price":30},
{"name":"strawberry","price":40}
]
I want to assign price values modfiedpricesarray to actutalpricesarray , so that the output of modfiedpricesarray will look like
[{"name":"apple","price":100},{"name":"orange","price":200},{"name":"strawberry","price":40}]
tried it this way
for(var i=0;i<modfiedpricesarray.length;i++)
{
var fruitnamemodfiedprice = modfiedpricesarray[i].name;
for(var j=0;j<actutalpricesarray.length;j++)
{
var fruitnameactualprice = actutalpricesarray[j];
if(fruitnamemodfiedprice==fruitnameactualprice)
modfiedpricesarray[i].price = actutalpricesarray[j].price;
}
}
console.log(JSON.stringify(modfiedpricesarray))
});
https://jsfiddle.net/o2gxgz9r/55230/
desired output of modfiedpricesarray should be
[
{"name":"apple","price":100},
{"name":"orange","price":200},
{"name":"strawberry","price":40}
]

Hey here is what you can do. I used the findIndex to get the index of the desired fruit then I update the price. Check my codepen too
var actutalpricesarray =[
{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
]
var modfiedpricesarray = [
{"name":"apple","price":20},
{"name":"orange","price":30},
{"name":"strawberry","price":40}
]
modfiedpricesarray.forEach((item,i) => {
var fruitnamemodfiedprice = item.name;
let index = actutalpricesarray.findIndex(x => x.name === fruitnamemodfiedprice);
if(index !== -1){
modfiedpricesarray[i].price = actutalpricesarray[index].price
}
})
console.log(JSON.stringify(modfiedpricesarray))

You can directly filter the array and then update value accordingly. You can test it below.
var actutalpricesarray = [{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
];
var modfiedpricesarray = [{
"name": "apple",
"price": 20
},
{
"name": "orange",
"price": 30
},
{
"name": "strawberry",
"price": 40
}
]
actutalpricesarray.forEach((data) => {
modfiedpricesarray.filter((d) => d.name == data.name).forEach((d) => d.price = data.price);
});
console.log(modfiedpricesarray);

Related

Replace keys based on another array of objects

I have two array of objects, Based on one array I need to replace the key of another array. Tried to use Object.Keys() but could not achieve it. Kindly suggest
// **Input :**
let sim = {
"header": [{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
}
// **Reference Array:**
let columns = [{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
]
/// **Code I tried**
for (let i = 0; i < sim.header.length; i++) {
if (Object.keys(sim[i].header) === Object.keys(columns[i].header)) {
sim[i].header[columns[i].header.FIELD_DESC] = sim[i].header[Object.keys(sim[i].header)]
}
}
console.log(sim);
Expected Output:
output = {
"header": [{
"Sales Organization": "1000",
"Distribution Channel: "
10 "
},
{
"Sales Organization": "1000",
"Distribution Channel": "20"
}
]
}
Is not perfect but try this
let sim = {
"header": [
{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
};
let columns = [
{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
];
const filter = {};
for (let i = 0; i < columns.length; i++) {
filter[columns[i].FIELD] = columns[i].FIELD_DESC;
}
sim.header = sim.header.map(el => {
const keys = Object.keys(el);
const newObj = {}
for (const key of keys) {
newObj[filter[key]] = el[key];
}
return newObj;
});
console.log(sim);
Here is an approach using Map and array.map . We store the columns as key value pair in Map , then while traversing the sim.header , just get the value from the map for the particular key and update it .
let sim = {
"header": [{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
}
let columns = [{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
]
var map = new Map();
columns.forEach(obj => {
map.set(obj.FIELD, obj.FIELD_DESC);
})
sim.header = sim.header.map(obj => {
var tempObj = {};
Object.keys(obj).forEach(key => {
tempObj[map.get(key)] = obj[key]
})
return tempObj;
})
console.log(sim);

Javascript -sort array based on another javascript object properties

I have one javascript array and one object . Need help to sort javascript object keys based on the order number in another array
In subgroup array , I have name , order number. Need to sort Offerings keys based on that order number
const subgroup = [
{
"code": "6748",
"name": "test123",
"orderNumber": "0"
},
{
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}
]
const offerings = {
"customdata" : [
{
"code": "Audi",
"color": "black"
}
],
"test123" : [
{
"brand": "Audi",
"color": "black"
}
]
}
I believe this should work for you. I've added some comments in the code that should hopefully do an okay job of explaining what is happening.
var subgroup = [{
"code": "6748",
"name": "test123",
"orderNumber": "0"
}, {
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}];
var offerings = {
"customdata": [{
"code": "Audi",
"color": "black"
}],
"test123": [{
"brand": "Audi",
"color": "black"
}]
}
function sortObjectFromArray(refArray, sortObject, orderKey = 'order', linkKey = 'key') {
// Get copy of refArray
let reference = refArray.slice();
// Sort sortObject [ into an array at this point ]
let sorted = [];
for (let key in sortObject) {
// Searches the refArray for the linkKey, and returns the intended index
let index = reference.find((item) => item[linkKey] === key)[orderKey];
// Places the sortObject's value in the correct index of the 'sorted' Array
sorted[parseInt(index)] = [key, sortObject[key]];
};
// Return an object, created from previous 'sorted' Array
return sorted.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
};
offerings = sortObjectFromArray(subgroup, offerings, 'orderNumber', 'name');
console.log(offerings);

Loop through possible arrays in json with typescript

I'm not asking how to loop through an array in typescript. My question is a bit different so let me explain first.
I have a json which looks like this:
{
"forename": "Maria",
"colors": [
{
"name": "blue",
"price": 10
},
{
"name": "yellow",
"price": 12
}
],
"items": [
{
"name": "sword",
"price": 20
}
],
"specialPowers": [
{
"name": "telekinesis",
"price": 34
}
]
},
{
"forename": "Peter",
"colors": [
{
"name": "blue",
"price": 10
}
],
"items": [
{
"name": "hat",
"price": 22
},
{
"name": "hammer",
"price": 27
}
]
}
// some more persons
As you can see, I have persons which can have arrays like colors, items or specialPowers. BUT a person can also have none of them. As you can see Maria has the array specialPowers, but Peter has not.
I need a function which checks if a person has one of these arrays and if so, I have to sum its price to a total. So I want the total price of all the things a person has.
At the moment I have three functions which basically look like this:
getTotalOfColors(person) {
let total = 0;
if(person.colors)
for (let color of person.colors) {
total = total + color.price;
}
return total;
}
getTotalOfItems(person) {
let total = 0;
if(person.items)
for (let item of person.items) {
total = total + item.price;
}
return total;
}
// SAME FUNCTION FOR SPECIALPOWERS
I basically have the same function for three times. The only difference is, that I'm looping through another array. But these functions do all the same. They first check, if the person has the array and secondly they loop through this array to add the price to a total.
Finally to my question: Is there a way to do this all in ONE function? Because they all are basically doing the same thing and I don't want redundant code. My idea would be to loop through all the arrays while checking if the person has the array and if so, adding its price to the total.
I assume the function would look something like this:
getTotal(person) {
let total = 0;
for (let possibleArray of possibleArrays){
if(person.possibleArray )
for (let var of person.possibleArray ) {
total = total + var.price;
}
}
return total;
}
Like this I would have a "universal" function but for that I have to have an array of the possible arrays like this: possibleArrays = [colors, items, specialPowers]
How do I achieve this? How and where in my code should I make this array ? Or is there even a better solution for this problem?
I created a function that seems to do the trick:
function totalPrice(data) {
let total = 0;
for (person of data) { //Go through the array of people
for (prop in person) { //Go through every property of the person
if (Array.isArray(person[prop])) { //If this property is an array
for (element of person[prop]) { //Go through this array
//Check if `price` is a Number and
//add it to the total
if (!isNaN(element.price)) total += element.price;
}
}
}
}
return total;
}
Demo:
function totalPrice(data) {
let total = 0;
for (person of data) {
for (prop in person) {
if (Array.isArray(person[prop])) {
for (element of person[prop]) {
if (!isNaN(element.price)) total += element.price;
}
}
}
}
return total;
}
let data = [
{
"forename": "Maria",
"colors": [{
"name": "blue",
"price": 10
},
{
"name": "yellow",
"price": 12
}
],
"items": [{
"name": "sword",
"price": 20
}],
"specialPowers": [{
"name": "telekinesis",
"price": 34
}]
},
{
"forename": "Peter",
"colors": [{
"name": "blue",
"price": 10
}],
"items": [{
"name": "hat",
"price": 22
},
{
"name": "hammer",
"price": 27
}
]
}
];
console.log(totalPrice(data));
You can use the function reduce and the function includes to select the desired targets.
var inputData = [{ "forename": "Maria", "colors": [{ "name": "blue", "price": 10 }, { "name": "yellow", "price": 12 } ], "items": [{ "name": "sword", "price": 20 }], "specialPowers": [{ "name": "telekinesis", "price": 34 }] }, { "forename": "Peter", "colors": [{ "name": "blue", "price": 10 }], "items": [{ "name": "hat", "price": 22 }, { "name": "hammer", "price": 27 } ] }];
function totalize(possibleArrays, data) {
return data.reduce((a, c) => {
return a + Object.keys(c).reduce((ia, k) => {
if (possibleArrays.includes(k)) c[k].forEach(p => ia += p.price);
return ia;
}, 0);
}, 0);
}
var total = totalize(["colors", "items", "specialPowers"], inputData);
console.log(total);
Something like this should also do it, I just logged the results in console, but you can do pretty much what you want with them :
const getSum = (person, prop) => {
let total = 0;
if(person[prop])
for (let value of person[prop]) {
total = total + value.price;
}
return total;
}
const props = ['colors', 'items', 'specialPowers']
console.log(data.map(person => props.map(prop => getSum(person, prop))));
Edit
I didn't get that you wanted to sum up all your properties for one person at once, this code is what I definitely what I would go for :
const sum = (a, b) => a + b;
const props = ['colors', 'items', 'specialPowers']
data.map(person =>
props.map(prop =>
(person[prop] || [])
.map(({price}) => price)
.reduce(sum, 0)
).reduce(sum, 0)
)
And if you want to sum all person's total price :
data.map(person =>
props.map(prop =>
(person[prop] || [])
.map(({price}) => price)
.reduce(sum, 0)
).reduce(sum, 0)
).reduce(sum, 0)

Create array from complex array objects & loops in javascript

I currently have a complex orders array (coming from a JSON client) that contains multiple orders like this (contains 2):
0: {
"employee": "Nicole"
"total": 13
"lineItems": {
"elements": [2]
0: {
"name": "Burger"
"price": 8
}
1: {
"name": "Lamb"
"price": 6.50
}
}
}
1: {
"employee": "Dan"
"total": 11
"lineItems": {
"elements": [2]
0: {
"name": "Lamb"
"price": 4.50
}
1: {
"name": "Meatballs"
"price": 6.50
}
}
}
What I want to do is create a new array that loops through the above and creates new items array based on the name of the lineItems object above. i.e. final output looks something like this:
var items = {
"Burger" = {
"totalSpent" : 8
},
"Lamb" = {
"totalSpent" : 13
// Note this totalSpent is an iteration or sum of all "price" items where name/id = "Lamb"
},
"Meatballs" = {
"totalSpent" : 4.50
}
}
I'm more used to PHP and have tried a number of different versions of this but can't seem to get the desired output. Here's what I've got so far:
var orders = //As above//
// Initialising new array to hold my final values
var orderItems = [];
for (var i = 0, len = orders.length; i < len; i++){
for(var e = 0, leng = orders[i]['lineItems']['elements'].length; e < leng; e++){
var totalSpent = 0;
var id = orders[i]['lineItems']['elements'][e]['name'];
if (orders[id] in orderItems[id]){
// overwrite existing array item
orderItems[id]['totalSpent'] += orders[i]['lineItems']['elements'][e]['price'];
orderItems[id].push({totalSpent : orderItems[id]['totalSpent']});
}
else {
// Create new array item
orderItems.push(id);
orderItems[id].push({totalSpent : orders[i]['lineItems']['elements'][e]['price']});
}
}
}
Edit:
Had to correct your orders syntax, I added it to my answer so you can run the Javascript Snippet;
Changed the whole dot notation to bracket notation to make it easier to read and understand;
Corrected the bug about items remaining an empty array (it was in the inner for);
var orders = [
{
"employee": "Nicole",
"total": 13,
"lineItems": {
"elements": [
{
"name": "Burger",
"price": 8
},
{
"name": "Lamb",
"price": 6.50
}
]
}
},
{
"employee": "Dan",
"total": 11,
"lineItems": {
"elements": [
{
"name": "Lamb",
"price": 4.50
},
{
"name": "Meatballs",
"price": 6.50
}
]
}
}
];
var items = {};
// loop in orders array
for (var i = 0; i < orders.length; i++) {
var elements = orders[i]["lineItems"]["elements"];
// loop in orders[i]["lineItems"]["elements"] object
for (var eIndex in orders[i]["lineItems"]["elements"]) {
// Add new item if it doesn't already exist
if (!items.hasOwnProperty(elements[eIndex]["name"])) {
items[elements[eIndex]["name"]] = {"totalSpent": elements[eIndex]["price"]};
} else {
// If it exists, sum totalSpent
items[elements[eIndex]["name"]]["totalSpent"] += elements[eIndex]["price"];
}
}
}
console.log(items);
PS: To find out why I'm using bracket notation instead of dot notation, check this question, it's good to know!
First of all, there are some error in your order array, note the difference between {} (for objects) and []. Then it is just simple use of the map function to iterate over the arrays.
See your browser console (F12) for the result of this snippet
var orders = [{
"employee": "Nicole",
"total": 13,
"lineItems": {
"elements": [{
"name": "Burger",
"price": 8
}, {
"name": "Lamb",
"price": 6.50
}
]
}
}, {
"employee": "Dan",
"total": 11,
"lineItems": {
"elements": [{
"name": "Lamb",
"price": 6.50
}, {
"name": "Meatballs",
"price": 4.50
}]
}
}]
var items = {}
orders.map(function(order) {
order.lineItems.elements.map(function(elem) {
if (items[elem.name]) {
items[elem.name].totalSpent += elem.price
} else {
items[elem.name] = {"totalSpent": elem.price}
}
})
})
console.log(items)

Search deep nested

I am working on a solution where I need to search for an element in a deeply nested JSON by its id. I have been advised to use underscore.js which I am pretty new to.
After reading the documentation http://underscorejs.org/#find , I tried to implement the solution using find, filter and findWhere.
Here is what I tried using find :
var test = {
"menuInputRequestId": 1,
"catalog":[
{
"uid": 1,
"name": "Pizza",
"desc": "Italian cuisine",
"products": [
{
"uid": 3,
"name": "Devilled chicken",
"desc": "chicken pizza",
"prices":[
{
"uid": 7,
"name": "regular",
"price": "$10"
},
{
"uid": 8,
"name": "large",
"price": "$12"
}
]
}
]
},
{
"uid": 2,
"name": "Pasta",
"desc": "Italian cuisine pasta",
"products": [
{
"uid": 4,
"name": "Lasagne",
"desc": "chicken lasage",
"prices":[
{
"uid": 9,
"name": "small",
"price": "$10"
},
{
"uid": 10,
"name": "large",
"price": "$15"
}
]
},
{
"uid": 5,
"name": "Pasta",
"desc": "chicken pasta",
"prices":[
{
"uid": 11,
"name": "small",
"price": "$8"
},
{
"uid": 12,
"name": "large",
"price": "$12"
}
]
}
]
}
]
};
var x = _.find(test, function (item) {
return item.catalog && item.catalog.uid == 1;
});
And a Fiddle http://jsfiddle.net/8hmz0760/
The issue I faced is that these functions check the top level of the structure and not the nested properties thus returning undefined. I tried to use item.catalog && item.catalog.uid == 1; logic as suggested in a similar question Underscore.js - filtering in a nested Json but failed.
How can I find an item by value by searching the whole deeply nested structure?
EDIT:
The following code is the latest i tried. The issue in that is that it directly traverses to prices nested object and tries to find the value. But my requirement is to search for the value in all the layers of the JSON.
var x = _.filter(test, function(evt) {
return _.any(evt.items, function(itm){
return _.any(itm.outcomes, function(prc) {
return prc.uid === 1 ;
});
});
});
Here's a solution which creates an object where the keys are the uids:
var catalogues = test.catalog;
var products = _.flatten(_.pluck(catalogues, 'products'));
var prices = _.flatten(_.pluck(products, 'prices'));
var ids = _.reduce(catalogues.concat(products,prices), function(memo, value){
memo[value.uid] = value;
return memo;
}, {});
var itemWithUid2 = ids[2]
var itemWithUid12 = ids[12]
I dont use underscore.js but you can use this instead
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function find(json,key,value){
var result = [];
for (var property in json)
{
//console.log(property);
if (json.hasOwnProperty(property)) {
if( property == key && json[property] == value)
{
result.push(json);
}
if( isArray(json[property]))
{
for(var child in json[property])
{
//console.log(json[property][child]);
var res = find(json[property][child],key,value);
if(res.length >= 1 ){
result.push(res);}
}
}
}
}
return result;
}
console.log(find(test,"uid",4));

Categories

Resources