change the value of objects of the array - javascript

Here's is my array
Array1 = [{year: "2013", fruit: "banana", quantity: 1},{year: "2014", fruit: "orange", quantity: 1},{year: "2014", fruit: "banana", quantity: 2}]
And my function to duplicate Array1:
var Array2 = Array1;
for (var i = 0, len = Array1.length; i < len; i++) {
Array2[i] = Array1[i];
}
But I'd like to change in Array2 all the values my key "year" and put the value "AllYear":
Array2 = [{year: "AllYear", fruit: "banana", quantity: 1},{year: "AllYear", fruit: "orange", quantity: 1},{year: "2014", fruit: "banana", quantity: 2}]

Use map, but make sure you return a new object:
var Array2 = Array1.map(function (el) {
return { fruit: el.fruit, year: 'AllYear', quantity: el.quantity }
});
DEMO

//js
var Array2 = Array1
for (var i = 0, len = Array1.length; i < len; i++) {
Array2[i].year = "AllYear";
}
refer this solution : Jsfiddle
I hope this will help !

you can do like this
Array2 = Array1.slice(0); //copy array1 elements to array2
Array2 = Array2.map(function (el) {
var copy = {};
for (var attr in el) {
if (el.hasOwnProperty(attr)) copy[attr] = el[attr];
}
copy.year = 'AllYear';
return copy ;
});

var Array2 = Array1;
$.each(Array2,function(index,value) {
value.year = "AllYear";
});//returns what you excepted

Related

Update the count value in an array

I have two array of objects arr 1 and arr 2
arr1 = [{fruit: 'apple',count: 0}] arr2 = [{fruit: 'apple',count: 0}]
Need to create the function which accepts arr1 and arr2 as arguments and compare the fruit name if its same need to update the count value based on the count input else push the value to the array
sample output 1:
Inputs:
arr1 = [{fruit: 'apple',count: 10}] arr2 = [{fruit: 'apple',count: 30},{fruit: 'orange',count: 20}]
Output:
[{fruit: 'apple',count: 40},{fruit: 'orange',count: 20}]
sample output2
Inputs:
arr1 = [{fruit: 'apple',count: 15}] arr2 = [{fruit: 'orange',count: 20}]
Output:
[{fruit: 'apple',count: 15},{fruit: 'orange',count: 20}]
code that i have tried:
function compareAndUpdateCount(arr1, arr2) {
for (i = 0; i < arr1.length; i++) {
if (arr1[i].fruit === arr2[i].fruit) {
arr1[i].count = arr1[i].count + arr2[i].count;
} else {
arr1.push(arr2[i])
}
}
}
This works fine when the array lengths are same ,if its different need help on writing the optimise code and also the reduce time complexity if we have more data
You will need a setter for count in your class
Make a new array of objects temparr
temparr[0] = arr1[0];
if((arr1[0].fruit).equals(arr2[0].fruit)) {
temparr[0].setcount(arr1[0].count+arr2[0].count);
}
else {
temparr[1]=arr2[0];
}
At the end u print temparr
You can easily achieve the result using Map and reduce
function groupObject(arr1, arr2) {
const map = new Map();
const temp = [...arr1, ...arr2].reduce((acc, { fruit, count }) => {
map.has(fruit)
? (map.get(fruit).count = map.get(fruit).count + count)
: map.set(fruit, { fruit, count });
return acc;
}, map);
return [...map.values()];
}
const arr1 = [{ fruit: "apple", count: 15 }];
const arr2 = [{ fruit: "orange", count: 20 }];
console.log(groupObject(arr1, arr2));
const arr3 = [{ fruit: "apple", count: 0 }];
const arr4 = [{ fruit: "apple", count: 0 }];
console.log(groupObject(arr3, arr4));
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
var result;
if(arr1.length < 1) {
result = arr2;
} else if(arr2.length < 1) {
result = arr1;
} else {
var existing = [];
var arr3 = [];
arr1.forEach(function (item, index) {
arr2.forEach(function (item2, index2) {
if(item.fruit === item2.fruit) {
item.count = item.count + item2.count;
existing.push(index2);
} else {
arr3.push(item);
if(!existing.includes(index2)) {
arr3.push(item2);
}
}
});
});
result = arr3;
}
Loop within another loop to compare all object properties and then use an if statement to sum up the counter and remove the item of the second array using splice()
Try the following snippet:
var arr1 = [{fruit: 'apple',count: 10}];
var arr2 = [{fruit: 'apple',count: 30}, {fruit: 'orange',count: 20}, {fruit: 'apple',count: 20}, {fruit: 'banana',count: 20}];
var counter = 0;
for(obj1 in arr1){
for(obj2 in arr2){
if (arr1[obj1].fruit === arr2[obj2].fruit) {
arr1[obj1].count = arr1[obj1].count + arr2[obj2].count;
arr2.splice(counter, 1);
counter++;
}
}
}
arr1 = arr1.concat(arr2);
console.log(arr1)
Try using reduce to group the fruits along with its count, followed by a simple map to get the required array
const arr1 = [{fruit: 'apple',count: 10}] , arr2 = [{fruit: 'apple',count: 30},{fruit: 'orange',count: 20}]
const res = [...arr1, ...arr2].reduce((acc, curr) => {
acc[curr.fruit]
? (acc[curr.fruit].count += curr.count)
: (acc[curr.fruit] = curr);
return acc;
}, {});
console.log(Object.keys(res).map((item) => res[item]));

Add Property to Object Array From Other Array - JS

I want to add a property to an array of objects from another existing array (both from the same length)
Example:
var array1 = [1, 2, 3];
var array2 = [{word: "hey"}, {word: "hello"}, {word: "world"}]
//Wanted Outcome: array2 = [{word: "hey", id: 1}, {word: "hello", id: 2}, {word: "world", id: 3}]
What I've tried:
for(var i=0; i<array1.length; i++){
for(var j= 0; j<array2.length; j++){
array2[j].id = array1[i];
}
}
//Outcome Im getting: array2 = [{word: "hey", id: 3}, {word: "hello", id: 3}, {word: "world", id: 3}]
How can I add a different property based on the first array length to the second array?
This is what you need
array2.forEach((item, i) => {
item.id = array1[i]
})
You don't need a nested loop here. Just you one level for loop and use i as both the indices
var array1 = [1, 2, 3];
var array2 = [{word: "hey"}, {word: "hello"}, {word: "world"}]
for(let i = 0; i < array2.length; i++){
array2[i].id = array1[i];
}
console.log(array2);
Cleaner way for doing this is to use map()
var array1 = [1, 2, 3];
var array2 = [{word: "hey"}, {word: "hello"}, {word: "world"}]
array2 = array2.map((x, i) => ({...x, id: array1[i]}));
console.log(array2);

Javascript - Map an array of strings to an array of objects with multiple object properties

So I have something like this:
var myArray = ["cherry", "Michigan", "potato", "Idaho", "apple", "NewYork", "Burrito", "California"]
I need to convert into:
[
{id: 1, foods: "cherry", location: "Michigan"},
{id: 2, foods: "potato", location: "Idaho"},
{id: 3, foods: "apple", location: "NewYork"},
{id: 4, foods: "burrito", location: "California"}
]
If your array data structure always be like that, you can do this:
var myArray = ["cherry", "Michigan", "potato", "Idaho", "apple", "NewYork", "Burrito", "California"]
let outputArr = []
let id = 1;
for(let i = 0; i < myArray.length -1; i +=2) {
outputArr.push({
id: id,
foods: myArray[i],
location: myArray[i+1]
})
id++;
}
console.log(outputArr)
You can loop you array in the following way:
const myArray = ["cherry", "Michigan", "potato", "Idaho", "apple", "NewYork", "Burrito", "California"]
let result = []
for(let i=0; i< myArray.length -1; i+=2) {
let id = result.length + 1
let foods = myArray[i]
let location = myArray[i+1]
result = [...result, {id, foods, location} ]
}
console.log(result)

New array of objects, but with changed keys

I have a problem with picking some data with array of objects and pushing it into new object (in different array), but in different way.
const fruits = [
{name: "apple"},
{name: "kiwi"},
{name: "banana"},
{name: "orange"},
{name: "pineapple"},
{name: "coconut"},
{name: "peach"},
{name: "lemon"}
]
I want to pick a few items from this and paste them into completely new array, so it could look like this:
const manyFruits = [
{name: "apple-banana-kiwi-coconut"},
{name: "orange-pineapple-peach-lemon"}]
It would be great to do a function which takes an argument of how many fruits we want to pick into new array and they shouldn't repeat.
Below is my code. Firstly I create new array with names, then I push them into new array which depends on "length" and finally I try to create new array with objects, but it fails.
const fruitArray = length => {
const fruits = [
{name: "apple"},
{name: "kiwi"},
{name: "banana"},
{name: "orange"},
{name: "pineapple"},
{name: "coconut"},
{name: "peach"},
{name: "lemon"}
]
const allFruits = []
for (let i = 0; i < fruits.length; i++) {
allFruits.push(fruits[i].name)
}
const newFruits =[]
for (let i = 0; i < length; i++) {
newFruits.push(allFruits[i])
}
const manyFruitsInOneArr = []
for (let i = 0; i < 2; i++) {
let newArr = {
name: newFruits.join("-"),
}
manyFruitsInOneArr[i] = (newArr)
}
console.log(manyFruitsInOneArr)
}
fruitArray(2)
It generates new objects in new array, but items are the same all the time.
You can create function for this using for loop and inside map() method to get array of names and join() to make a string from values.
const fruits = [{"name":"apple"},{"name":"kiwi"},{"name":"banana"},{"name":"orange"},{"name":"pineapple"},{"name":"coconut"},{"name":"peach"},{"name":"lemon"}]
const pick = (arr, n) => {
const r = [];
for (var i = 0; i < arr.length; i += n) {
const name = arr
.slice(i, i + n)
.map(({name}) => name)
.join('-');
r.push({name})
}
return r;
}
const result = pick(fruits, 2)
console.log(result)
Update: to get names and sum of energy for each slice you can use map() and reduce() methods.
fruits = [ {name: "apple", energy: 100}, {name: "kiwi", energy: 126}, {name: "banana", energy: 150}, {name: "orange", energy: 118}, {name: "pineapple", energy: 98}, {name: "coconut", energy: 83}, {name: "peach", energy: 65}, {name: "lemon", energy: 36} ]
const pick = (arr, n) => {
const r = [];
for (var i = 0; i < arr.length; i += n) {
const slice = arr.slice(i, i+n);
const name = slice.map(({name}) => name).join('-')
const energy = slice.reduce((r, {energy}) => r + energy, 0);
r.push({name, energy})
}
return r;
}
const result = pick(fruits, 2)
console.log(result)
That could be done using recursion:
function subset(arr, n){
if(!(n - 1)) return [arr[0].name];
const result = [];
for(let i = 0; i < arr.length - n; i++){
for(const sub of subset(arr.slice(i + 1), n - 1)){
result.push(arr[i].name + "-" + sub);
}
}
return result;
}
So you can do:
subset(fruits, 5);

Concatenate two JSON objects

I have two JSON objects with the same structure and I want to concat them together using Javascript. Is there an easy way to do this?
Based on your description in the comments, you'd simply do an array concat:
var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);
// jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23},
//{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
If you'd rather copy the properties:
var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };
function jsonConcat(o1, o2) {
for (var key in o2) {
o1[key] = o2[key];
}
return o1;
}
var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);
Output of above code is{ value1: '1', value2: '4', value3: '3' }
The actual way is using JS Object.assign.
Object.assign(target, ...sources)
MDN Link
There is another object spread operator which is proposed for ES7 and can be used with Babel plugins.
Obj = {...sourceObj1, ...sourceObj2}
I use:
let x = { a: 1, b: 2, c: 3 }
let y = {c: 4, d: 5, e: 6 }
let z = Object.assign(x, y)
console.log(z)
// OUTPUTS:
{ a:1, b:2, c:4, d:5, e:6 }
From here.
You can use jquery extend method.
Example:
o1 = {"foo":"bar", "data":{"id":"1"}};
o2 = {"x":"y"};
sum = $.extend(o1, o2);
Result:
sum = {"foo":"bar", "data":{"id":"1"}, "x":"y"}
One solution is to use a list/array:
var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};
var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);
Result
jsons = [
{"name":"joe", "age":27},
{"name":"james", "age":32}
]
if using TypeScript, you can use the spread operator (...)
var json = {...json1,...json2}
You can use Object.assign() method. The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.[1]
var o1 = { a: 1 }, o2 = { b: 2 }, o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.
json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';
json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';
concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));
Just try this, using underscore
var json1 = [{ value1: '1', value2: '2' },{ value1: '3', value2: '4' }];
var json2 = [{ value3: 'a', value4: 'b' },{ value3: 'c', value4: 'd' }];
var resultArray = [];
json1.forEach(function(obj, index){
resultArray.push(_.extend(obj, json2[index]));
});
console.log("Result Array", resultArray);
Result
var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}
I use:
let jsonFile = {};
let schemaJson = {};
schemaJson["properties"] = {};
schemaJson["properties"]["key"] = "value";
jsonFile.concat(schemaJson);
The simplest way :
const json1 = { value1: '1', value2: '2' };
const json2 = { value2: '4', value3: '3' };
const combinedData = {
json1,
json2
};
console.log(combinedData)
I dont know if you want this:
U can use this for create from arrays, all arrays need contains the same number of elments.
Example:
If you have:
let a = ["a", "b", "c"];
let b = [1, 2, 3];
Use
concatArraysLikeJson([a, b]);
The result of is:
let result = {
0 : ["a", 1],
1 : ["b", 2],
2 : ["c", 3]
};
Typescript
concatArraysLikeJson(arrays:any){
let result:any = {};
let size:number = 0;
let make:boolean = true;
if(arrays.length > 0){
size = arrays[0].length;
for(let i = 1; i < arrays.length; i++){
let array = arrays[i];
if(make){
if(array.length != size){
make = false;
}
}
}
}
if(make){
for (let o = 0; o < size; o++) {
result[o] = [];
}
for(let i = 0; i < arrays.length; i++){
const array = arrays[i];
//console.log(array);
for (let o = 0; o < size; o++) {
const element = array[o];
result[o].push(element);
}
}
return result;
}else{
return false;
}
}
Javascript:
concatArraysLikeJson(arrays){
let result = {};
let size = 0;
let make = true;
if(arrays.length > 0){
size = arrays[0].length;
for(let i = 1; i < arrays.length; i++){
let array = arrays[i];
if(make){
if(array.length != size){
make = false;
}
}
}
}
if(make){
for (let o = 0; o < size; o++) {
result[o] = [];
}
for(let i = 0; i < arrays.length; i++){
const array = arrays[i];
//console.log(array);
for (let o = 0; o < size; o++) {
const element = array[o];
result[o].push(element);
}
}
return result;
}else{
return false;
}
}
The JSON Objects and Arrays can be combined in multiple ways within a structure
I can merge json with rules using json-object-merge
import JSONObjectMerge from "json-object-merge";
const target = {
store: {
book: [
{
category: "reference",
author: "Nigel Rees",
title: "Sayings of the Century",
price: 8.95
}
],
bicycle: {
color: "red",
price: 19.95
}
}
};
const source = {
store: {
book: [
{
category: "fiction",
author: "Evelyn Waugh",
title: "Sword of Honour",
isbn: "0-679-43136-5",
price: 12.99
}
]
}
};
const merged = JSONObjectMerge(target, source, { "$.store.book": "PREPEND" });
expect(merged).toEqual({
store: {
book: [
{
// books from source are prepended to the original array
category: "fiction",
author: "Evelyn Waugh",
title: "Sword of Honour",
isbn: "0-679-43136-5",
price: 12.99
},
{
category: "reference",
author: "Nigel Rees",
title: "Sayings of the Century",
price: 8.95
}
],
bicycle: {
color: "red",
price: 19.95
}
}
});

Categories

Resources