Read specific value of an object - javascript

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" ]

Related

JS: Check for existence of deep object key and replace value

I am wanting to develop a function to check for the existence of a key within a deep object and then replace the value of that key with a data set from another object.
E.g.
var obj = {
"id": 1,
"component": "Preset 1",
"priority": 1,
"header": {
"modeSet": 2
}
}
const modeSets = [
{
"id": 1
"name": "Mode Set 1"
},
{
"id": 2
"name": "Mode Set 2"
}
]
function obtainModeSets(obj){
//...
}
When the function obtainModeSets runs I'd like to mutate obj so that the value of modeSet within obj equals { "id": 2 "name": "Mode Set 2" }
Does anyone have any suggestions? Thanks
You can use recursion like this
const obj = {
"id": 1,
"component": "Preset 1",
"priority": 1,
"header": {
"modeSet": 2
}
}
const modeSets = [{
"id": 1,
"name": "Mode Set 1"
},
{
"id": 2,
"name": "Mode Set 2"
}
]
function obtainModeSets(obj) {
Object.entries(obj).forEach(([key, value]) => {
if (key === "modeSet") {
obj[key] = modeSets.find(set => set.id === value)
return
}
if (typeof value === "object") {
obtainModeSets(value)
}
})
}
obtainModeSets(obj)
console.log(obj)
I think something like the below code maybe solves your problem. I don't know what you mean exactly. But based on the showing example, I guess you need to replace your key with the id provided in the modeSets.
function obtainModeSets(obj, key, cb){
// loop through all possible keys
Object.keys(obj).forEach(k => {
if (key === k) {
obj[k] = cb(obj[k])
}
// if the value of the key is object, just go inside
if (typeof obj[k] === "object") {
obtainModeSets(obj[k], key, cb)
}
})
}
// you can call your function like this
obtainModeSets(obj, 'modeSet', (val) => {
return modeSets.find(mode => mode.id === val)
})

How to update object except current index in Angular 8

this.StaticData = {
"values": [
{
"value": "test",
"label": "test"
},
{
"value": "aa",
"label": "bb"
},
{
"value": "cc",
"label": "dd"
}
]
};
I have above object of data. I wanted to return all object except currentIndex.
For example -
suppose in above objects, if I am going to edit 0th index values,
and I have updated "value": "rest", instead of "value": "test" and
"label": "test" need to keep as it is. So in that case,
it will allow to update the values.
{
"value": "rest",
"label": "test"
},
But if I tried to enter "label": "bb" and "label": "dd",
so it will return false, because these values are already available in above objects.
isLabelExist() {
const formData = this.editStaticParametersForm.value;
const currentIndex: number = this.StaticData.values.indexOf(this.selectedRowValue);
if (formData.label_value && this.StaticData) {
var isPresent = this.StaticData.values.some(function (el) {
return el.label === formData.label_value
});
if (isPresent) {
return false;
}
}
return true;
}
using find (or some) you can check the "index" (add a second argument to the function find), so,
var isPresent = this.StaticData.values.some(function (el,i) {
return el.label === formData.label_value && i!=currentIndex
});
Really in .ts we use arrow flat and use const or let, not var
const isPresent = this.StaticData.values.some((el,i)=> {
return el.label === formData.label_value && i!=currentIndex
});
Or
const isPresent = this.StaticData.values.some(
(el,i)=> el.label === formData.label_value && i!=currentIndex);

Filter array based property value [duplicate]

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)

Loop through JSON array of objects and get the properties based on the matching IDs from objects

My target is if the id from digital_assets and products matches then get the value of URL fro digital_assets and ProductName from products object. I'm able to traverse through the object and get the values of digital_assets and products but need some help to compare these two objects based on IDs to get the value of URL and ProductName. Below is what I've done so far.
var data = [{
"digital_assets": [{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}]
}, {
"products": [{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},{
"id": ["BB002", "AA002"],
"ProductName": "PROD 555"
}]
}
];
$.each(data, function () {
var data = this;
//console.log(data);
$.each(data.digital_assets, function () {
var dAssets = this,
id = dAssets['id'];
// console.log(id);
});
$.each(data.products, function () {
var proData = this,
prod_id = proData['id'];
// console.log(prod_id);
$.each(prod_id, function () {
var arr_id = this;
console.log(arr_id);
});
});
});
Do I need to create new arrays and push the values into the new arrays? Then concat() these array to one. ? Bit lost any help will be appreciated.
Here is one way you can do this via Array.reduce, Array.includes, Object.entries and Array.forEach:
var data = [{ "digital_assets": [{ "id": "AA001", "url": "https://via.placeholder.com/150" }, { "id": "AA002", "url": "https://via.placeholder.com/150" } ] }, { "products": [{ "id": ["BB001", "AA001"], "ProductName": "PROD 485" }, { "id": ["BB002", "AA002"], "ProductName": "PROD 555" } ] } ]
const result = data.reduce((r,c) => {
Object.entries(c).forEach(([k,v]) =>
k == 'digital_assets'
? v.forEach(({id, url}) => r[id] = ({ id, url }))
: v.forEach(x => Object.keys(r).forEach(k => x.id.includes(k)
? r[k].ProductName = x.ProductName
: null))
)
return r
}, {})
console.log(Object.values(result))
You can use Array.prototype.find, Array.prototype.includes and Array.prototype.map to achieve this very gracefully.
let data = [
{
"digital_assets": [
{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},
{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}
]
},
{
"products": [
{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},
{
"id": ["BB002","AA002"],
"ProductName": "PROD 555"
}
]
}
];
// Find the 'digital_assets' array
let assets = data.find(d => d['digital_assets'])['digital_assets'];
// Find the 'products' array
let products = data.find(d => d['products'])['products'];
// Return an array of composed asset objects
let details = assets.map(a => {
return {
id : a.id,
url : a.url
name : products.find(p => p.id.includes(a.id)).ProductName
};
});
console.log(details);
changed answer to fit your needs:
var data = [
{
"digital_assets": [
{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},
{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}
]
},
{
"products": [
{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},
{
"id": ["BB002","AA002"],
"ProductName": "PROD 555"
}
]
}
]
let matchingIds = [];
let data_assetsObject = data.find(element => {
return Object.keys(element).includes("digital_assets")
})
let productsObject = data.find(element => {
return Object.keys(element).includes("products")
})
data_assetsObject["digital_assets"].forEach(da => {
productsObject["products"].forEach(product => {
if (product.id.includes(da.id)){
matchingIds.push({
url: da.url,
productName: product.ProductName
})
}
})
})
console.log(matchingIds);
working fiddle: https://jsfiddle.net/z2ak1fvs/3/
Hope that helped. If you dont want to use a new array, you could also store the respective data within the element you are looping through.
Edit:
I think i know why i got downvoted. My example works by making data an object, not an array. changed the snippet to show this more clearly.
Why is data an array anyway? Is there any reason for this or can you just transform it to an object?
Edit nr2:
changed the code to meet the expectations, as i understood them according to your comments. it now uses your data structure and no matter whats in data, you can now search for the objects containing the digital_assets / products property.
cheers
https://jsfiddle.net/2b1zutvx/
using map.
var myobj = data[0].digital_assets.map(function(x) {
return {
id: x.id,
url: x.url,
ProductName: data[1].products.filter(f => f.id.indexOf(x.id) > -1).map(m => m.ProductName)
};
});

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
}
});

Categories

Resources