Copy array from one array to another and change values while copying - javascript

I have two arrays:
dataArray1 = [{
"id":1
"addressDetails": {55:1,56:20}
},
{
"id":2
"addressDetails": {55:30,56:10}
}
]
Above array contains addressDetails as object.
dataArray2= [{
"id":1
"addressDetails": [
{
"addressId": "55",
"city":"london",
"code":1
},
{
"addressId": "56",
"city":"paris",
"code":1
}
]
},
{
"id":2
"addressDetails": [
{
"addressId": "55",
"city":"london",
"code":0
},
{
"addressId": "56",
"city":"paris",
"code":0
}
]
}
]
This second array contains arrayDetails as array.
In both the arrays, id and addressId will be same. On the basis of both these id's I need to replace addressDetails object in dataArray1 by addressDetails array of dataArray2. In this replacement, I need to change value of "code" property of addressDetails array with the right hand side value(value on right side in addressDetailObject) for that particular id and addressId. For example, for Id "1" and addressId "55", in addressDetails object - "addressDetails": {55:1,56:10} value is "1", so I need to change value of "code" property in addressDetailsArrays with 1 and copy rest attritubtes as it is. How can I do that?

For this you can run
let result = array1.map((item) => {
//code to change item here
//find address value of array2 based on id and addressId
//replace the code with the address.code details you found above
});
What we are doing here is iterating over items of array1 and returning an updated value for each item.

Related

get all items that have match with other array

I'm creating a query but i came a section when i don't have idea that how do it. I have one array that have for example two items
//filter array
const filterArray=r.expr(['parking', 'pool'])
and also i have one table with follows records:
[
{
"properties": {
"facilities": [
"parking"
],
"name": "Suba"
}
},
{
"properties": {
"facilities": [
"parking",
"pool",
"pet friendly"
],
"name": "Kennedy",
}
},
{
"properties": {
"facilities": [
"parking",
"pool"
],
"name": "Soacha"
}
},
{
"properties": {
"facilities": [
"parking",
"pet friendly",
"GYM"
],
"name": "Sta Librada"
}
},
]
I need filter the records with the array but i need that record has all items of array filter. If the record has more item of array filter not is problem, i need if contains all items of array filter get that record. On this case I need all records that have the facilities "pool" and "parking"
Current query
Current query but it also return records with one or two items of the filter array
r.db('aucroom').table('hosts')
.filter(host=>
host('properties')('facilities').contains(val=>{
return filterArray.contains(val2=>val2.eq(val))
})
)
.orderBy('properties')
.pluck(['properties'])
results that I desire wait
Like the image example:
If you want a strict match of two arrays (same number of elements, same order), then use .eq()
array1.eq(array2)
If you want the first array to contain all elements of the second array, then use .setIntersection(), just note array2 should contain distinct elements (a set):
array1.setIntersection(array2).eq(array2)

Filter out objects in array if one value is the same

I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.
For example, I might get back:
[
{
"Name": "blah",
"Date": "1992-02-18T00:00:00.000Z",
"Language": "English",
},
{
"Name": "blahzay",
"Date": "1998-02-18T00:00:00.000Z",
"Language": "French",
}, {
"Name": "blah", // same name, no problem
"Date": "1999-02-18T00:00:00.000Z", // different date
"Language": "English", // but same language
},
]
So I want to check that no two objects have a key with the same "Language" value (in this case, "English").
I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.
There is an example here:
Unexpeected result when filtering one object array against two other object arrays
but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.
I would be looking for a way to compare
arrayName[eachObject].Language === "English"
and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().
The below snippets stores the languages that have been encountered in an array. If the current objects language is in the array then it is filtered out. It makes the assumption that the first object encountered with the language is stored.
const objs = [
{
"Name": "blah",
"Date": "1992-02-18T00:00:00.000Z",
"Language": "English",
},
{
"Name": "blahzay",
"Date": "1998-02-18T00:00:00.000Z",
"Language": "French",
}, {
"Name": "blah", // same name, no problem
"Date": "1999-02-18T00:00:00.000Z", // different date
"Language": "English", // but same language
},
],
presentLanguages = [];
let languageIsNotPresent;
const objsFilteredByLanguage = objs.filter(function (o) {
languageIsNotPresent = presentLanguages.indexOf(o.Language) == -1;
presentLanguages.push(o.Language);
return languageIsNotPresent;
});
console.log(objsFilteredByLanguage);
You could take a hash table and filter the array by checking Name and Language.
var array = [{ Name: "blah", Date: "1992-02-18T00:00:00.000Z", Language: "English" }, { Name: "blahzay", Date: "1998-02-18T00:00:00.000Z", Language: "French" }, { Name: "blah", Date: "1999-02-18T00:00:00.000Z", Language: "English" }],
hash = {},
result = array.filter(({ Name, Language }) => {
var key = `${Name}|${Language}`;
if (!hash[key]) return hash[key] = true;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using Set makes it easy to remove duplicates for as many keys as you like. I tried to be as verbose as possible so that each step was clear.
var objects = [{ "Name": "blah", "Date": "1992-02-18T00:00:00.000Z", "Language": "English", }, { "Name": "blah", "Date": "1998-02-18T00:00:00.000Z", "Language": "French", }, { "Name": "blah", "Date": "1999-02-18T00:00:00.000Z", "Language": "English" }];
function uniqueKeyVals(objects, key) {
const objVals = objects.map(object => object[key]); // ex. ["English", "French", "English"]
return objects.slice(0, new Set(objVals).size); // ex. { "English", "French" }.size = 2
}
function removeKeyDuplicates(objects, keys) {
keys.forEach(key => objects = uniqueKeyVals(objects, key));
return objects;
}
// can also use uniqueKeyVals(key) directly for just one key
console.log("Unique 'Language': \n", removeKeyDuplicates(objects, ["Language"]));
console.log("Unique ['Language', 'Name']: \n", removeKeyDuplicates(objects, ["Language", "Name"]));
I would use the underscore module for JavaScript and the unique function in this scenario. Here is a sample array of data objects:
let data = [{
name: 'blah',
date: Date.now(),
language: "en"
},
{
name: 'noblah',
date: Date.now(),
language: 'es'
},
{
name: 'blah',
date: Date.now(),
language: 'en'
}];
Then we can use the unique function in the underscore library to only return a copy of the data that has unique values associated with the language key:
const result = _.unique(data, 'language');

Adding a Object Array in a Array into a JSON

I had this JSON:
"event": [
{
"timestamp": "2016-10-02T11:37:31.2300892-03:00",
"revenue": 120.0,
"transaction_id": "3409340",
"store_name": "BH Shopping",
"products": []
}
And this Object Array:
[ { name: 'Blue Shirt', price: 100 },
{ name: 'Nike Shoes', price: 150 } ]
How can I add the Object Array into the products Array inside the JSON using Javascript?
Please check this solution of adding objects to object property:
var jsonStr = '{"event": {"timestamp": "2016-10-02T11:37:31.2300892-03:00", "revenue": "120.0", "transaction_id": "3409340", "store_name": "BH Shopping", "products": []}}';
var obj = JSON.parse(jsonStr);
obj['event']['products'].push({"name":"Blue Shirt","price":"100"});
obj['event']['products'].push({"name":"Nike Shoes","price":"150"});
jsonStr = JSON.stringify(obj);
console.log(jsonStr);
From the look of it, event is a JSON Array on its own so to target the first one you will have to pict JSON Object at index 0.
var eventObject = event[0];
Now the products is an array and you can push staff into it by iterating over your Object Array
objectArray.forEach(function(object){
//the object is each array item
eventObject.products.push(object);
});

javascript - accessing specific data in an array of objects

How do I pick the first value of rowVal of the first object (I want to print 42.00).
dataTest.rows = [{
"rowHeader": "",
"rowDesc": ["Gene Name"],
"rowVal": [
["42.00", "57.00", "45.00", "48.00", "52.00", "47.00", "39.00", "38.00", "35.00"]
]
}, {
"rowHeader": "",
"rowDesc": ["Gene Source"],
"rowVal": [
["38.00", "50.00", "39.00", "41.00", "45.00", "40.00", "34.00", "33.00", "29.00"]
]
}];
I tried:
console.log(dataTest.rows[0].rowVal[0]);
but it returns all the numbers in the array of rowVal of the first object?
rowVal is an Array of Arrays. That's why you get that result.
"rowVal": [
["38.00", "50.00", "39.00", "41.00", "45.00", "40.00", "34.00", "33.00", "29.00"]
]
See, when you say rowVal[0], it refers to an array. So, ideally, it should be something like
"rowVal": ["38.00", "50.00", "39.00", "41.00", "45.00", "40.00", "34.00", "33.00", "29.00"]
if you want to access the elements as rowVal[0]. Or else, you have to change your reference to rowVal[0][0].

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

Categories