I need to store data coming from an api in a variable. Only data that contains "true". I have given the API output below.
API Output Data
{
"BNG-JAY-137-003": false,
"BNG-JAY-137-004": true,
"BNG-JAY-137-005": false
}
Below is my function. In this I need to store only data which is true in a variable. Here selected_data is a variable which contains API data.
on(){
for(let key in this.selected_data) {
if(this.selected_data[key]) {
// here I need to store data which is true in an array.
}
}
}
There are several ways to do this. One would be to use Object.keys and filter:
const selected_data = this.selected_data
const array = Object.keys(selected_data).filter(key => selected_data[key])
Closer to your original code would be to just push the keys onto an array:
const selected_data = this.selected_data
const array = []
for (const key in selected_data) {
if (selected_data[key]) {
array.push(key)
}
}
From a Vue perspective this would probably be implemented as a computed property, returning the relevant array at the end. Alternatively it might be stored in a data property, using something equivalent to this.propertyName = array at the end of the method.
You could use a computed property:
computed: {
valid_selected_data: function() {
return Object.keys(this.selected_data).reduce((acc, key) => {
if(this.selected_data[key]) {
acc[key] = this.selected_data[key];
}
return acc;
}, {});
}
}
That code will create another object which holds the same items of your selected_data object, but only the true ones.
If you want just an array with the true keys, then try this:
computed: {
valid_selected_data: function() {
return Object.keys(this.selected_data).filter((key) => this.selected_data[key]);
}
}
Related
I have 5 arrays namely and in order to decrease the amount of code I am trying to add all arrays in a single object and push that object into local storage. Later retrieve the object and use the properties. But when the user iam console logging the object, it is showing property values as undefined. I want that when the user first time enters the site and there is no data in the local storage object, then an object with empty array values should be pushed to local storage, something like this:-
{videoData: [],playlistName: [],playlistObj: [],videoIds: [],notesArr: []}
But instead object with undefined values is being pushed:-
{videoData: undefined,playlistName: undefined,playlistObj: undefined,videoIds: undefined,notesArr: undefined}
Function to retrieve data =
const getStoredDataFunc = () => {
let videoData = localStorage.getItem(`storageData`)
if (videoData) {
return JSON.parse(localStorage.getItem(`storageData`))
}
else {
return {
videoData: [],
playlistName: [],
playlistObj: [],
videoIds: [],
notesArr: []
}
}
}
console.log(getStoredDataFunc) // {}
States:-
const [videoData, setvideoData] = useState(getStoredDataFunc().videoData);
const [playlistName, setplaylistName] = useState(getStoredDataFunc().playlistName)
const [playlistObj, setplaylistObj] = useState(getStoredDataFunc().playlistObj)
const [videoIds, setvideoIds] = useState(getStoredDataFunc().videoIds)
const [notesArr, setnotesArr] = useState(getStoredDataFunc().notesArr)
Add to local storage -
useEffect(() => {
let obj = {
videoData: videoData,
playlistName: playlistName,
playlistObj: playlistObj,
videoIds: videoIds,
notesArr: notesArr
}
localStorage.setItem("storageData", JSON.stringify(obj))
}, [videoData, playlistObj, playlistName, videoIds, notesArr])
Maybe when you're setting the data in these arrays in state, it's overwriting [] to undefined.
Can you share the code logic about how you're using these setter functions -setvideoData, setplaylistName etc.
I have an array of objects in my DB records.
The record:
{"ID123":{"FileID":"12345","FileName":"ABCFile_ver5_44453.PDF"},"DocID":6009,"DocFormat":"PDF"}
The format to store the filename in my DB is always with "FileName": "actual_fileName.PDF".
I want to only get the object with "FileName":"....", to only display the filename instead of other objects.
This is my code:
getValue(): Atts[] | any {
if (this.isEmptyValue()) {
return [];
}
return !this.useObject ? this.value : Object.entries(this.value).map(([key, value]) => ({ key, value })).filter(value=);
}
How do I filter the object that contains "FileName" so that I can display the filename in my application?
I'm stuck at the filter method.
I had to reduce your code a little to a minimal reproducible example, and I made the assumption that this.value in your Object.entries is the entire DB record that you have listed above. I converted this to an object so I could process it in my code. So, your mileage may vary if my assumption was incorrect.
let obj = {
"ID123": {
"FileID": "12345",
"FileName": "ABCFile_ver5_44453.PDF"
},
"DocID": 6009,
"DocFormat": "PDF"
};
let result = { "FileName": Object.entries(obj).map(([key, value]) => ({
key,
value
})).filter(keyValuePair => {
if (keyValuePair.value.FileName) {
return true;
}
})[0].value.FileName };
This returns:
{
"FileName": "ABCFile_ver5_44453.PDF"
}
Your filter step is filtering an array of key value pairs, so when filtering, you need to return true only if the 'value' is an object that has a property of FileName.
EDIT:
I realized that the way I wrote this will not work if the returned object from the array does not have value (or is undefined), so it's probably a better idea to store this in a variable first, and then return an object based on that varible, like so:
let fileNameObj = Object.entries(obj).map(([key, value]) => ({
key,
value
})).filter(keyValuePair => {
if (keyValuePair && keyValuePair.value.FileName) {
return true;
}
})[0];
if (fileNameObj && fileNameObj.FileName) {
let result = { "FileName": fileNameObj.FileName };
}
I have an array of all items ids:
const allIds = ['a1gb', 'f4qa', 'i9w9']
I also have an object with it's properties having those ids as keys:
const byId = {
a1gb: {
whatever1
},
anyOtherIdThatIDontNeed: {
whatever444
},
f4qa: {
whatever2
},
i9w9: {
whatever3
}
}
What is the most common way to return an array that would look like
[ { whatever1 }, { whatever2 }, { whatever3 } ]
and skip the Ids I don't want in my final array?
This a log of the array with the ids:
This is a log of the object from which I need to return an array with the values of the keys from that array of ids skipping the ones I don't need:
P.S. Problem is that in that return array from the map function I get undefined when it encounters "anyOtherIdThatIDontNeed:".
P.P.S.[ ANSWER ] - The array of Ids had ids that do not match object's keys and that is why I was getting undefined.
var result = allids.map(val => ({byId[val]}))
I would suggest this way, try the below code if the array also has unwanted ids.
var result = allids.map(val => ({byId[val]})).filter(val => val?true:false)
I have an object, which looks like this:
{
'somename1':{
status:'success',
data:{
key:'value1',
field2:'',
field3:'',
field4:'',
field5:'',
recordSts:'done',
}
},
'someOtherName':{
status:'success',
data:{
key:'value2',
field2:0,
field3:'',
recordSts:'progress',
field5:'',
field6:0,
}
}
}
In this object, I have two fields key and recordSts, which are not null if the status is success.
I want to filter this object using lodash and the output should look like this
{
'somename1':{
status:'success',
data:{
key:'value1',
status:'value1',
}
},
'someOtherName':{
status:'success',
data:{
key:'value1',
status:'value1',
}
}
}
Simply I want to delete the keys which having null or empty or 0 values.
I tried this:
_.map(records, 'key'); //records contains my input object
But it gives only the value of one field, instead, I want the name of the field and the second field also. Please help.
Thanks.
You can use _.pickBy with our custom predicate, like
_.forEach(records, function(record) {
record.data = _.pickBy(record.data, function(val) {
return !!val;
}
})
you can use _.omitBy to remove falsy values
let res = _.forOwn(records, o => {
o.data = _.omitBy(o.data, v => {
return !v;
});
return o;
});
You can use mapValues(), assign(), and pickBy():
_.mapValues(
records,
r => _.assign({}, r, { data: _.pickBy(r.data) })
);
This produces a new records object, without mutating the original. What I like about pickBy() is that by default, it'll only return properties with truthy values. Notice how we're not passing a predicate? This works because the default predicate is identity(), which simply uses the value as a truth test.
Quick question guys, I am combining two objects using spread syntax, the new object is sorted automatically by keys of previous two objects, I dont want my new object to be sorted by keys (because I want users to see older conversations in my redux state above and newly fetched conversations). What can I do?
Here is my reducer, that takes array of conversations (array has 3 conversations first time around, and then +1 with another hit), and create objects based on conversation id
case actions.SET_CONVERSATION_MESSAGES: {
let convos = {};
payload.chatinbox.forEach(message => {
if (state[ message.chatsession_id ]) {
convos = Object.assign(convos, {
[ message.chatsession_id ]: {
messages: [...state[ message.chatsession_id ].messages, message]
}
});
} else if (!state[ message.chatsession_id ]) {
convos = Object.assign(convos, {
[ message.chatsession_id ]: {
messages: [message]
}
});
}
});
return {
...convos,
...state
};
}
here is how state object look
{
14632: {},
14652: {},
14741: {}
}
and when a new conversation comes in that has a key that fits in between
{
14542: {}
}
the new object get automatically sorted by them
{
14632: {},
14542: {},
14652: {},
14741: {}
}
and the result that I want is
{
14632: {},
14652: {},
14741: {},
14542: {}
}
for obvious reason, to show user what is fetched before and what is fetched afterwards, what can I do?
Objects don't guarantee order, so the keys can be shuffled around depending on browser implementation. If you want order to be maintained, consider using an array of objects with ids instead.
If you're using the IDs for direct access to the object, you might find array.find helpful if you transition to using an array of objects with IDs.