Filter array based property value [duplicate] - javascript

This question already has answers here:
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Closed 3 years ago.
I have a JSON file containing 13k objects. I need to get only the objects which have the events { name: "Submitted"} property from it. events is an array of objects which contain multiple name properties. Here is a screenshot of how it looks:
{
"_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
"_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
"doctype": "application",
"events": [{
"name": "change",
"time": 1532547503182
},
{
"name": "change",
"time": 1532547503182
},
{
"name": "submitted",
"time": 1532547503182
},
{
"name": "edited",
"time": 1532547503182
}
]
}
This is how I get all the object inside the json file:
$.getJSON("export.json", function(data) {
var data = [];
var arrays = data;
var i;
for (i = 0; i < arrays.length; i++) {
console.log(arrays[i]);
}
});
Now I need to push all the objects which have events[name:submitted] I get in arrays[i] into the doc[]. How can I filter the results?

You can filter your array of the object by filter method.
$.getJSON("export.json", function(data) {
var data = [];
var arrays = data;
var newArray = arrays.filter(function (el) {
return el.name == 'Submitted';
});
console.log(newArray);
});
You can also do in one line using ES6 arrow function
var newArray = arrays.filter(el => el.name === 'Submitted')

You can use filter(), checking each element in the events array to see if the name is equal to submitted:
const object = {
"_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
"_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
"doctype": "application",
"events": [{
"name": "change",
"time": 1532547503182
},
{
"name": "change",
"time": 1532547503182
},
{
"name": "submitted",
"time": 1532547503182
},
{
"name": "edited",
"time": 1532547503182
}
]
}
const filtered = object.events.filter(obj => obj.name === 'submitted')
console.log(filtered)

Related

How to convert value into key & another key into value in JavaScript [duplicate]

This question already has answers here:
How to convert array of key–value objects to array of objects with a single property?
(5 answers)
Closed 1 year ago.
This is my array of Object. I want to convert my first value into key & Second value into value only. Please go through question and i have also attached my desired output.
[
{
"name": "Unknown",
"value": "RAHUL"
},
{
"name": "FirstName",
"value": "WILLEKE LISELOTTE"
},
{
"name": "LastName",
"value": "DE BRUIJN"
}
]
I want my Object as
{
"Unknown": "RAHUL"
},
{
"FirstName": "WILLEKE LISELOTTE"
},
{
"LastName": "DE BRUIJN"
}
IF you mean to create a new array, then simply map the original array. You don't need to create a new array and push into it, that's just redundant code:
const testData = [{
"name": "Unknown",
"value": "RAHUL"
},
{
"name": "FirstName",
"value": "WILLEKE LISELOTTE"
},
{
"name": "LastName",
"value": "DE BRUIJN"
}
];
const newData = testData.map(nameObject => {
return {
[nameObject.name]: nameObject.value
}
});
console.log(newData);
You just have to use brackets for [value.name] to perform achieve this.
var arr = []
testdata.map((value) => {
arr.push({ [value.name]: value.value })
})

Read specific value of an object

I'm using an api that return this object:
{
"0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
"0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
}
I need to extract the value A0242 and LZZMRN55L53C003Z but the only things that I know are the name "Codice+tessera" and "Codice+fiscale". How can I read these values? Maybe my question is stupid but really I'm losing my brain today...
Thanks
You can try this:
const data = {
"0155894402285712": {
"type": "GBUserFieldText",
"value": "A0242",
"name": "Codice+tessera"
},
"0155894402283800": {
"type": "GBUserFieldText",
"value": "LZZMRN55L53C003Z",
"name": "Codice+Fiscale"
}
};
// get an array of all the values of this data.
const arrayOfValues = Object.values(data);
// filter this array in order to find the one which the name you want
const selectedObj = arrayOfValues.find(obj => obj.name === 'Codice+tessera');
// get the value of this object.
const selectedValue = selectedObj.value;
console.log(selectedValue);
// You can also make a function findValueOf(name):
const findValueOf = name =>
arrayOfValues.find(obj => obj.name === name) &&
arrayOfValues.find(obj => obj.name === name).value;
// and use it for example:
console.log(findValueOf('Codice+tessera')); // "A0242"
console.log(findValueOf('Codice+Fiscale')); // "LZZMRN55L53C003Z"
You can use Object.values and then access value key's value
let obj = {
"0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
"0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
}
Object.values(obj).forEach(({value})=>{
console.log(value)
})
You can use Object.values to convert the object into an array. Use map to loop and get the value
var obj = {"0155894402285712":{"type":"GBUserFieldText","value":"A0242","name":"Codice+tessera"},"0155894402283800":{"type":"GBUserFieldText","value":"LZZMRN55L53C003Z","name":"Codice+Fiscale"}}
var resut = Object.values(obj).map(o => o.value);
console.log(resut);
If you want to match the name and value, you can use reduce
var obj = {"0155894402285712":{"type":"GBUserFieldText","value":"A0242","name":"Codice+tessera"},"0155894402283800":{"type":"GBUserFieldText","value":"LZZMRN55L53C003Z","name":"Codice+Fiscale"}}
var resut = Object.values(obj).reduce((c, v) => Object.assign(c, {[v.name]: v.value}), {});
console.log(resut);
If you are looking to find A0242 from the value "Codice+tessera" that you have, you need something different than the other answers:
var data = {
"0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
"0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
}
const values = ["Codice+tessera", "Codice+fiscale"]
const results = values.map(v => Object.values(data).find(datum => datum.name === v)).map(v => v.value)
console.log(results) // [ "A0242", "LZZMRN55L53C003Z" ]

cannot update an array of elements via a 2d iteration

I have two arrays of object, the first array (printerChart, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
},
....
]
The second array (items, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "hp"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do is to iterate via the second array and, if the part of the name of an item (i.e. DT8) is included in an element of the array 'compatibility' of the first array, I would like to include a new properties to it from the element of the first array: printerBrand. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
items.forEach((item) => {
printerChart.forEach((printer) => {
if (printer.compatibilty.some(compatibleElem => (
item.name.includes(compatibleElem)))) {
item.printerBrand = printer.printerBrand;
} else {
item.printerBrand = '';
}
});
});
What am I doing wrong?
You do
items.items.forEach(...)
Shouldn't you be doing
items.forEach(...)
?
I suggest to initialize item.printerBrand with an empty string and use a nested approach of some for getting a brand and to exit the loops, if found.
This prevents to get an empty string even if there is a brand to assign.
items.forEach((item) => {
item.printerBrand = '';
printerChart.some(printer => {
if (printer.compatibilty.some(compatibleElem => item.name.includes(compatibleElem))) {
item.printerBrand = printer.printerBrand;
return true;
}
});
});

How to append object-key value form one array to other array?

I have an existing array with multiple object. With an interval I would like to update the existing array with values from another array. See the (simplified) example below.
I've serverall gools:
Copy the value of fan_count form the new array, to the current array with the key "fan_count_new"
If a object is removed or added in the New array, it have to do the same to the Current array.
As far I can see now, I can use some es6 functions :) like:
object-assign, but how to set the new key "fan_count_new"?
How to loop through the array to compare and add or remove + copy the fan_count?
Current array:
[{
"fan_count": 1234,
"id": "1234567890",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
},
{
"fan_count": 4321,
"id": "09876543210",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
}, ...
]
New array:
[{
"fan_count": 1239,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
"id": "1234567890"
},
{
"fan_count": 4329,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
},
"id": "09876543210"
}, ...
]]
You can remove elements which doesn't exists in new array by using array.filter and you can loop through the new array to update the same object in the current array:
var currArr = [
{
"fan_count": 1234,
"id": "1234567890",
},
{
"fan_count": 4321,
"id": "09876543210",
},
{
"fan_count": 4321,
"id": "09876543215",
}
];
var newArr = [
{
"fan_count": 1234,
"id": "1234567890"
},
{
"fan_count": 5555,
"id": "09876543210"
}
];
currArr = currArr.filter(obj => newArr.some(el => el.id === obj.id));
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
found.fan_count_new = obj.fan_count;
}
});
console.log(currArr);
Later on I realised that is was better to turn it around, add the fan_count form the currArr to the new one. This because it is easier to handle new objects, and you dont't have to deal with deleted objects. So, anybody how is looking for something like this:
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
console.log('found: ', found.fan_count, obj.fan_count)
obj.fan_count_prev = found.fan_count;
obj.fan_count_diff = Math.round(obj.fan_count - found.fan_count);
}
if (typeof obj.fan_count_prev === "undefined") {
obj.fan_count_prev = obj.fan_count;
obj.fan_count_diff = 0
}
});

node.js - Sort JSON objects by a value [duplicate]

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 5 years ago.
I have this JSON file on my server:
{"1504929411112":{"name":"user1","score":"10"},"1504929416574":{"name":"2nduser","score":"14"},"1504929754610":{"name":"usr3","score":"99"},"1504929762722":{"name":"userfour","score":"40"},"1504929772310":{"name":"user5","score":"7"}}
Assuming I have parsed this file:
var json = JSON.parse(getJSONFile());
How can I now sort each object in the json variable by the score property?
None of the array sorting functions work for me as json is not an array.
Since these are objects' properties, their order is usually unknown and not guaranteed. To sort them by some internal property, you would first have to change the Object into an Array, for example:
const json = JSON.parse(getJsonFile());
const jsonAsArray = Object.keys(json).map(function (key) {
return json[key];
})
.sort(function (itemA, itemB) {
return itemA.score < itemB.score;
});
For more, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
var ob = { "fff": { "name": "user1", "score": "10" }, "bbbb": { "name": "user4", "score": "14" }, "dddd": { "name": "user2", "score": "99" }, "cccc": { "name": "user5", "score": "40" }, "aaaa": { "name": "user3", "score": "7" } };
Object.keys(ob).map(key => ({ key: key, value: ob[key] })).sort((first, second) => (first.value.name < second.value.name) ? -1 : (first.value.name > second.value.name) ? 1 : 0 ).forEach((sortedData) => console.log(JSON.stringify(sortedData)));

Categories

Resources