Object assign overrides previous object when values are the same - javascript

So I am expecting this object when using Object.assign on object1 and object2. There is unknown number of objects 1 - n range.
var expectedObject = [{
"question": {
"value": "foo"
},
"question2": {
"value": "foo1"
},
"question3": {
"value": ["fooArray"]
}
},
{
"question": {
"value": "foo1"
},
"question2": {
"value": "foo2"
},
"question3": {
"value": ["foo1Array"]
}
}];
var object1 = {
"question": {
"value": "foo"
},
"question2": {
"value": "foo1"
},
"question3": {
"value": ["fooArray"]
}
};
var object2 = {
"question": {
"value": "fooIOverrideYouSucker"
},
"question2": {
"value": "fooIOverrideYouSucker1"
},
"question3": {
"value": ["fooIOverrideYouSuckerWonArray"]
}
}
var allItems = {};
// This will be running inside loop - object1 and object2 are just an examples to simplify the case
Object.assign(allItems, object1, object2);
console.log(JSON.stringify([allItems]));
The results I am getting:
[{
"question": {
"value": "fooIOverrideYouSucker"
},
"question2": {
"value": "fooIOverrideYouSucker1"
},
"question3": {
"value": ["fooIOverrideYouSuckerWonArray"]
}
}]
Is there a nice way to simply append multiple same objects into existing object?
Thank you.
Fiddle with above example.
https://jsfiddle.net/bielus86/fad4w2Lo/10/

If you are looking to create an array with the two objects, you can simply do [object1, object2] or
var allItems = [];
allItems.push(object1);
allItems.push(object2);

Related

find if an array is inside another nested array

I 'm trying to find if array1 is is inside the nested array2.data.
const array1 = [
{
name: "Color",
value: "Yellow",
},
{
name: "Size",
value: "Small",
},
];
const array2 = [
{
"id": 1,
"data": [
{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Small"
}
]
},
{
"id": 2,
"data": [
{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Medium"
}
]
},
{
"id": 3,
"data": [
{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Large"
}
]
},]
this is what I have tread but not giving me the result I need :
array2.map(( a ) => {
a.data.map(( data ) => {
array1.map((option) => {
if( data === option) {
return data;
}
});
});
});
JSON.stringify() the needle array (array1) and the data attribute of each array member in array2 and compare the two; if they match, array1 is present in array2:
const array1 = [{
name: "Color",
value: "Yellow",
},
{
name: "Size",
value: "Small",
},
];
const array2 = [{
"id": 1,
"data": [{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Small"
}
]
},
{
"id": 2,
"data": [{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Medium"
}
]
},
{
"id": 3,
"data": [{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Large"
}
]
},
];
const dataArrayIsPresentInArray2 = needle => !!array2.find(cv => JSON.stringify(cv.data) === JSON.stringify(needle));
console.log(dataArrayIsPresentInArray2(array1)); // true
As mentioned in the comments, this method will only work for data structures serializable with JSON.stringify().
If the order of the objects in array1 does not matter, you can iterate through every item and use Array.every to check whether each item in the data property after stringification is equal to an item in array1 after stringification.
const array1=[{name:"Color",value:"Yellow"},{name:"Size",value:"Small"}],array2=[{id:1,data:[{name:"Color",value:"Yellow"},{name:"Size",value:"Small"}]},{id:2,data:[{name:"Color",value:"Yellow"},{name:"Size",value:"Medium"}]},{id:3,data:[{name:"Color",value:"Yellow"},{name:"Size",value:"Large"}]}];
const contains = array2.some(e => e.data.every(f => array1.some(g => JSON.stringify(g) == JSON.stringify(f))));
console.log(contains)
if you wanna just to check if arr1 in arr2.date
i would probably just
loop over arr2.data and compare each iteration to arr1 and if it is the same return or change some value to know the output .
something like :
// var that represent if arr1 inside arr2.data
let arr1InsideArr2= false
for (let i of array2){
if (i.data == array1){
return arr1InsideArr2= true
}
}
and then do with the var arr1InsideArr2 whatever you want to check .

Look up values in an array using looping forEach Google Apps Script Javascript

I have an object that looks like the following {key: id numbers}
var obj = {
"c4ecb": {id: [3]},
"a4269": {id: [34,36]},
"d76fa": {id: [54,55,60,61]},
"58cb5": {id: [67]}
}
How do I loop each above id in the following array, and return the label?
var response =
{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}
Finally, what I want to do is look up the key and return a string of id values.
For example, input c4ecb and output strawberry. Input a4269 and output lettuce, radish. Input d76fa and output "spaghetti, rigatoni, lasagna, fettuccine"
I think to join the multiple labels output into one string I could use something like
array.data.vegetables.map(vegetables => vegetables.value).join(', ')].toString();
So in the end I want to have something like
var fruits = [some code that outputs "strawberry"];
var vegetables = [some code that outputs "lettuce, radish"];
var pasta = [some code that outputs "spaghetti, rigatoni, lasagna, fettuccine"];
What I've tried so far:
The following loop will return the id only if there is one id to be called for: e.g. only in case one where {id: 3} but returns null in cases like {id: 34,36} (because it's looking for '34,36' in id, which doesn't exist - I need to look for each one individually.
response.data.forEach(({key, options}) => {
if (obj[key]) {
options.forEach(({id, label}) => {
if (id == obj[key].id) obj[key].label = label;
});
}
});
console.log(obj)
Filter the response object to focus on the category that matches the id.
Map over the options array and select the items which appear in obj[id].
Finally convert the filtered results to a string.
See filteredLabelsAsString() function below for implementation.
var obj = {
"c4ecb": {"id": [3]},
"a4269": {"id": [34,36]},
"d76fa": {"id": [54,55,60,61]},
"58cb5": {"id": [67]}
}
var response =
[{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}];
function filteredLabelsAsString(obj_key, obj, content=response) {
// sanity check: obj must contain obj_key
if (Object.keys(obj).includes(obj_key)) {
return content.filter((item) => {
// filter content using value of obj_key
return item.data[0].key == obj_key;
}).map((item) => {
// item : { success: true, data: [] }
// map over options array
return item.data[0].options.map((opt) => {
// option : {id, label}
// return the label if the id is in the obj object's list
if (obj[item.data[0].key].id.includes(opt.id))
return opt.label;
}).filter((label) => {
// filter out empty items
return label !== undefined;
});
}).join(",");
}
// if obj does not contain obj_key return empty string
return "";
}
console.log("fruits: " + filteredLabelsAsString("c4ecb", obj));
console.log("vegetables: " + filteredLabelsAsString("a4269", obj));
console.log("pasta: " + filteredLabelsAsString("d76fa", obj));

Check if value doesn't exist in JSON object

I want to check if a value doesn't exist in the given object, by filtering an array of string.
I want to check if the values in the keys array are contained in the JSON object I'm looping. If one of the values isn't, I have to do something else, but only if the non-existent value (in resArray) is contained in the keys array.
JSON here
Here's what I tried:
var keys = [
"total_kills",
"total_deaths",
"total_planted_bombs",
"total_defused_bombs",
"total_kills_knife",
"total_kills_headshot",
"total_wins_pistolround",
"total_wins_map_de_dust2",
"last_match_wins",
"total_shots_fired",
"total_shots_hit",
"total_rounds_played",
"total_kills_taser",
"last_match_kills",
"last_match_deaths",
"total_kills_hegrenade",
];
var resArray = stats.playerstats.stats;
var statsArray = [];
for (var i = 0; i < keys.length; i++) {
for(var j = 0; j < resArray.length; j++){
//if the value in keys array exists, do something
if(resArray[j]["name"] === keys[i]){
//do something
}
if(<value doesn't exist)>)
//do something else.
}
}
Solved:
function contains(obj, key, value) {
return obj.hasOwnProperty(key) && obj[key] === value;
}
var resArray = stats.playerstats.stats;
var statsArray = [];
for (var i = 0; i < keys.length; i++) {
resArray.some(function(found){
if(contains(found, "name", keys[i])){
statsArray.push(found);
}
});
if(typeof statsArray[i] == 'undefined'){
console.log("Not present in array: " + keys[i]);
statsArray.push({"name": keys[i], "value": 'None'});
}
}
Thanks to everyone has replied to this thread.
Your example insinuates that you're creating a new array based off the stats and conditional presence of your provided keys. An easy way to build this array would be to use Array.prototype.map to enumerate over your stats array. Next, in each iteration's callback you can pass the name property as an argument to keys.indexOf to check if that particular name is present in your keys array.
var statsArray = stats.map(function(stat) {
if (keys.indexOf(stat.name) > -1) {
return stat;
} else {
return stat.name + ' not found.';
}
});
This will yield a new array which will contain either the stat object or a not regarding its absence in keys. However, you can return whatever your heart desires, as long as it's a valid array item.
Here's a working example with a small chunk of your dataset (but will work with your original dataset):
var keys = [
"total_kills",
"total_deaths",
"total_planted_bombs",
"total_defused_bombs",
"total_kills_knife",
"total_kills_headshot",
"total_wins_pistolround",
"total_wins_map_de_dust2",
"last_match_wins",
"total_shots_fired",
"total_shots_hit",
"total_rounds_played",
"total_kills_taser",
"last_match_kills",
"last_match_deaths",
"total_kills_hegrenade",
];
var stats = [{
"name": "total_kills",
"value": 25305
}, {
"name": "total_deaths",
"value": 27474
}, {
"name": "total_time_played",
"value": 1822419
}, {
"name": "total_planted_bombs",
"value": 1397
}, {
"name": "total_defused_bombs",
"value": 239
}, {
"name": "total_wins",
"value": 11477
}, {
"name": "total_damage_done",
"value": 3783962
}, {
"name": "total_money_earned",
"value": 65159500
}, {
"name": "total_rescued_hostages",
"value": 1
}, {
"name": "total_kills_knife",
"value": 278
}, {
"name": "total_kills_hegrenade",
"value": 168
}, {
"name": "total_kills_glock",
"value": 699
}, {
"name": "total_kills_deagle",
"value": 1289
}, {
"name": "total_kills_elite",
"value": 37
}, {
"name": "total_kills_fiveseven",
"value": 165
}, {
"name": "total_kills_xm1014",
"value": 78
}, {
"name": "total_kills_mac10",
"value": 154
}, {
"name": "total_kills_ump45",
"value": 330
}, {
"name": "total_kills_p90",
"value": 1105
}, {
"name": "total_kills_awp",
"value": 6934
}, {
"name": "total_kills_ak47",
"value": 4528
}, {
"name": "total_kills_aug",
"value": 137
}, {
"name": "total_kills_famas",
"value": 540
}, {
"name": "total_kills_g3sg1",
"value": 116
}, {
"name": "total_kills_m249",
"value": 50
}, {
"name": "total_kills_headshot",
"value": 7112
}, {
"name": "total_kills_enemy_weapon",
"value": 2308
}, {
"name": "total_wins_pistolround",
"value": 843
}, {
"name": "total_wins_map_cs_assault",
"value": 9
}, {
"name": "total_wins_map_cs_italy",
"value": 15
}, {
"name": "total_wins_map_cs_office",
"value": 11
}, {
"name": "total_wins_map_de_aztec",
"value": 71
}, {
"name": "total_wins_map_de_cbble",
"value": 373
}, {
"name": "total_wins_map_de_dust2",
"value": 4857
}, {
"name": "total_wins_map_de_dust",
"value": 25
}, {
"name": "total_wins_map_de_inferno",
"value": 777
}, {
"name": "total_wins_map_de_nuke",
"value": 247
}, {
"name": "total_wins_map_de_train",
"value": 47
}, {
"name": "total_weapons_donated",
"value": 2466
}, {
"name": "total_broken_windows",
"value": 30
}, {
"name": "total_kills_enemy_blinded",
"value": 566
}, {
"name": "total_kills_knife_fight",
"value": 67
}, {
"name": "total_kills_against_zoomed_sniper",
"value": 2284
}, {
"name": "total_dominations",
"value": 270
}, {
"name": "total_domination_overkills",
"value": 225
}, {
"name": "total_revenges",
"value": 207
}, {
"name": "total_shots_hit",
"value": 83704
}, {
"name": "total_shots_fired",
"value": 399207
}, {
"name": "total_rounds_played",
"value": 23419
}, {
"name": "total_shots_deagle",
"value": 12137
}, {
"name": "total_shots_glock",
"value": 21299
}, {
"name": "total_shots_elite",
"value": 777
}, {
"name": "total_shots_fiveseven",
"value": 3385
}, {
"name": "total_shots_awp",
"value": 22667
}];
var statsArray = stats.map(function(stat) {
if(keys.indexOf(stat.name) > -1) {
return stat;
} else {
return stat.name + ' not present in keys';
}
});
console.log(statsArray);
You can achieve what you want by using a combination of array functions. For example:
let stats = data.playerstats.stats;
let matches = stats.filter(i => keys.indexOf(i.name) >= 0);
let matchKeys = matches.map(k => k.name);
let negatives = keys.filter(i => matchKeys.indexOf(i) < 0);
Then you can just loop through the matches/negatives to do what you want with them.
Fiddle here.

Create JSON structure from JSON result that has many records

Friends, further to my question regarding Creating JSON structure from JSON results how can i create my object that has many headers from the array?
Here is my Fiddle and my code is below.
var array = [
[{
"label": "NewNetworkServiceProvider",
"value": "NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "PurchaseOrderNumber",
"value": "PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "RawRecordType",
"value": "RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5b1ad"
}],
[{
"label": "NewNetworkServiceProvider",
"value": "NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "PurchaseOrderNumber",
"value": "PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "RawRecordType",
"value": "RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5m321"
}]
];
var obj = {
header: {}
};
array.forEach(function (item) {
item.forEach(function (data) {
obj.header[data.label] = data.value;
});
});
console.log(obj)
At a guess I think you want this:
array.forEach(function (item) {
item.forEach(function (data) {
obj.header[data.label] = obj.header[data.label] || [];
obj.header[data.label].push(data.value);
});
});
http://jsfiddle.net/867mb14s/1/
Your array is incorrect. the JS code you provided works perfectly if you have different label names, if label names are same then the latest values will replace the old values.
So , try this code. it gives all header names.
var array = [
[{
"label": "0_NewNetworkServiceProvider",
"value": "0_NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "0_PurchaseOrderNumber",
"value": "0_PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "0_RawRecordType",
"value": "0_RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5b1ad"
}],
[{
"label": "1_NewNetworkServiceProvider",
"value": "1_NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "1_PurchaseOrderNumber",
"value": "1_PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "1_RawRecordType",
"value": "1_RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5m321"
}]
];
var obj = {
header: {}
};
array.forEach(function(item) {
item.forEach(function(data) {
obj.header[data.label] = data.value;
});
});
console.log(obj)
See the difference in array data.
And #Jaromanda X is also correct, but he is fetching records as array inside each header.

Transform/parse javascript object key value pairs

I have an object that looks like this:
{
"KeyValueOfstringstring": [
{
"Key": "FET",
"Value": "123"
},
{
"Key": "FFS2",
"Value": "Z"
},
{
"Key": "LoadIndex",
"Value": "91"
},
{
"Key": "Ply",
"Value": "B"
}
]
}
and i want it to look like this:
{
"KeyValueOfstringstring": [
{
"FET": 123,
"FFS2": "Z",
"LoadIndex": "91",
"Ply": "B"
}
]
}
Has anyone done this before or has any idea how this could be accomplished? Unfortunately this is the response from a WS and thus have to work with it.
You can do it with a regular for loop:
var result = {};
for (var i = 0; i < object.array_with_long_name.length; i++) {
var o = object.array_with_long_name[i];
result[o.Key] = o.Value;
}

Categories