I have an api data
current: {
errors: {},
items: {
Economy: {}
}
}
Object key "Economy" can be different, for instance "Advance"
and i call it like
let current = current.items.Economy
or let current = current.items.Advance
How can i call it dynamically?
P.S. My front don't know what key will be return
Use Object.entries to get every key and value pair in an object. If items only has one such key-value pair, then just select the first entry:
const obj = {
current: {
errors: {},
items: {
Foo: {data: 'foo data'}
}
}
};
const [key, val] = Object.entries(obj.current.items)[0];
console.log(key);
console.log(val);
If you don't actually care about the dynamic key name and just want the inner object, use Object.values instead.
You can use Object.keys(current.items).
let current = {
errors: {},
items: {
Economy: {age: 10}
}
}
let keys = Object.keys(current.items);
let currentVal = current.items[keys[0]];
console.log(currentVal);
You can also use for loop:
let current = {
errors: {},
items: {
Economy: {age: 10}
}
}
for(var key in current.items){
console.log(current.items[key]);
}
Related
I am trying to get all object to append in a div but my updated values are not coming. If I assign a value while assigning my object, Object.entries can get all values.
My objects:
var allObjects = {
ivSetObject : {
id: "ivSet",
url: "../assets/img/ivSet.png"
},
gloveObject : {
id: "glove",
url: "../assets/img/glove.png"
},
tourniqueObject: {
id: "tournique",
url: "../assets/img/tournique.png"
},
trashObject: {
id: "trash",
url: "../assets/img/trash.png"
},
glove2Object: {
id: "glove2",
url: "../assets/img/glove.png"
},
ivSet2Object: {
id: "ivSet2",
url: "../assets/img/ivSet.png"
}
};
var selectedObjects = {};
I am adding values from here:
outerDiv.onclick = function () {
Object.defineProperty(selectedObjects, key, {
value: value
});
createSelectedDivs();
};
I am trying to call values from here:
var selectedContainer = document.getElementById("selectedItems");
function createSelectedDivs() {
console.log(selectedObjects);
selectedContainer.innerHTML = "";
for (const [key, value] of Object.entries(selectedObjects)) {
console.log("aa");
const outerDiv = document.createElement("div");
outerDiv.className = "selectedItemCard";
const imgDiv = document.createElement("img");
imgDiv.src = value.url;
outerDiv.appendChild(imgDiv);
selectedContainer.appendChild(outerDiv);
}
}
I can see selectedObjects in console.log but Object.entries(selectedObjects) is not working.
Based on mdn docs
Normal property addition through assignment creates properties which show up during property enumeration (for...in, Object.keys(), etc.), [...]. This method allows these extra details to be changed from their defaults. By default, properties added using Object.defineProperty() are not writable, not enumerable, and not configurable.
Your code:
const obj = {}
Object.defineProperty(obj, 'key', {
value: 'value'
})
console.log(Object.entries(obj))
With enumarable: true:
const obj = {}
Object.defineProperty(obj, 'key', {
value: 'value',
enumerable: true
})
console.log(Object.entries(obj))
The issue here is that Object.entries() returns an array of an object's enumerable properties and values, but does not update after the object has been modified. This means that if you update an object, the entries returned by Object.entries() will not reflect the changes.
To fix this, you need to call Object.entries() again after updating the object to get the updated values. For example:
let obj = {
a: 1,
b: 2
};
let entries = Object.entries(obj);
obj.a = 3;
// To get the updated values, we need to call Object.entries again
entries = Object.entries(obj);
console.log(entries); // [['a', 3], ['b', 2]]
I have an array arr with the below format
data:{
result: [Array]
}
I am mapping an array and setting key and values to form new array like this.
const userData= arr.map((user) => ({
userid : user.data.result[0].info.uid,
termStat: user.data.result[0].info['attr'].termStat
}));
This will give me the userData array as
[{
userid: 'y74',
termStat:[[Object]]
}]
How can I make this to the below format. Placing key as the value of userid.
This is the expected result
{
y74: { termStat: [[Object]]
}
You can set the key as the userid.
const arr = [{
data: {
result: [
{
info: {
uid: 12,
attr: {
termStat: 'foobar'
}
}
}
]
}
}]
const userData= arr.map(user => ({
[user.data.result[0].info.uid]: {
'termStat': user.data.result[0].info['attr'].termStat
}
}));
console.log(userData)
Array map function always returns an array. If you want to return a map from the input array Array.reduce() function will be helpful. Something like:
const arr = [{ data: { result: [{ info: { uid: 'y74', attr: { termStat: [[{}]] } } }] } }];
const userData = arr.reduce((result, user) => {
const key = user.data.result[0].info.uid;
const termStat = user.data.result[0].info['attr'].termStat;
result[key] = {termStat};
return result;
}, {});
console.log(userData);
Hope this helps :)
You can just use the userid as a variable putting it in a square brackets and assing it a value if I understand it correctly
[user.data.result[0].info.uid]: {'termStat': user.data.result[0].info['attr'].termStat}
I have an Array of objects and one object
const filterArray = [{bestTimeToVisit: 'Before 10am'}, {bestDayToVisit: Monday}]
This values are setting in a reducer and the payload will be like
{bestTimeToVisit: 'After 10am'}
or
{bestDayToVisit: Tuesday}.
So what I need is when I get a payload {bestTimeToVisit: 'After 10am'} and if bestTimeToVisit not in filterList array, then add this value to the filterList array.
And if bestTimeToVisit already in the array with different value, then replace the value of that object with same key
if(filterArray.hasOwnProperty("bestTimeToVisit")) {
filterArray["bestTimeToVisit"] = payload["bestTimeToVisit"];
} else {
filterArray.push({"bestTimeToVisit": payload["bestTimeToVisit"]});
}
I convert the object array into a regular object and then back into an object array. makes things less complicated. I'm making the assumption each object coming back only has one key/value and that order doesnt matter.
const objectArraytoObject = (arr) =>
arr.reduce((acc, item) => {
const key = [Object.keys(item)[0]];
return { ...acc, [key]: item[key] };
}, {});
const newValues = [{ someKey: 'something' }, { bestDayToVisit: 'Tuesday' }];
const filterArray = [
{ bestTimeToVisit: 'Before 10am' },
{ bestDayToVisit: 'Monday' },
];
const newValuesObj = objectArraytoObject(newValues);
const filterObj = objectArraytoObject(filterArray);
const combined = { ...filterObj, ...newValuesObj };
const combinedToArray = Object.keys(combined).map((key) => ({
[key]: combined[key],
}));
console.log(combinedToArray);
Need to iterate over the array and find objects that satisfy for modification or addition if none are found.
function checkReduced(filterrray,valueToCheck="After 10am"){
let isNotFound =true;
for(let timeItem of filterrray) {
if(timeItem.bestTimeToVisit && timeItem.bestTimeToVisit !== valueToCheck) {
timeItem.bestTimeToVisit=valueToCheck;
isNotFound=false;
break;
}
}
if(isNotFound){filterrray.push({bestTimeToVisit:valueToCheck})}
}
const filterArray = [{bestDayToVisit: "Monday"}];
checkReduced(filterArray,"After 9am");//calling the function
const updateOrAdd = (arr, newItem) => {
// get the new item key
const newItemKey = Object.keys(newItem)[0];
// get the object have the same key
const find = arr.find(item => Object.keys(item).includes(newItemKey));
if(find) { // the find object is a reference type
find[newItemKey] = newItem[newItemKey]; // update the value
} else {
arr.push(newItem); // push new item if there is no object have the same key
}
return arr;
}
// tests
updateOrAdd([{ a: 1 }], { b: 2 }) // => [{ a: 1 }, { b: 2 }]
updateOrAdd([{ a: 1 }], { a: 2 }) // => [{ a: 2 }]
I'm getting a list of objects as a response like this
As you can see the objects are not in an array. I want to push these objects into an array. I tried the following way
this.setState({
countrydata: this.state.countrydata.push(datasnapshot.val()),
})
But it didn't work. What's the correct approach to push these objects into an array?
PS:
componentDidMount() {
const countryCode = this.props.match.params.countryCode;
var countryName = getName(countryCode);
var firebaseHeadingref = firebase.database().ref(countryCode);
firebaseHeadingref.once('value').then(datasnapshot => {
this.setState({
countrydata: datasnapshot.val(),
countryName: countryName,
loading: false
})
});
}
I think that the "countrydata" in a dict not an array.
Try to initialize the it as an empty array.
Array.prototype.push returns the new length of the array after the push, so you are essentially setting the state to a number.
You are not allowed to mutate the array with React state, you need to create a new array containing your new elements:
// When updating state based on current state, use the function form of setState.
this.setState(state => {
countrydata: [...state.countrydata, datasnapshot.val()],
})
This is assuming countryData is indeed an array, which from your screenshot, it appears to not (it seems to be an object), so you may be set something wrong somewhere along the way (or datasnapshot.val()) doesn't contain what you think it contains.
You could do this:
const keys = Object.keys(countryData); // array of the keys ["place_1", ...]
const array = Array(keys.length); // Prepares the output array of the right size
for (let i=0; i<keys.length; i++) {
const country = countryData[keys[i]]; // get the next country object
country.key = keys[i]; // add the key into the object if you need it
array[i] = country; // store the value into the array at index 'i'
}
// array now is [ {key: "place_1", description: "Sigiriya Rock Fortress"}, ...]
this.setState({countryDataArray: array});
You could try something like this. Array.prototype.push().
I have not tested below code.
componentDidMount=async() =>{
const countryCode = this.props.match.params.countryCode;
var countryName = getName(countryCode);
var firebaseHeadingref = firebase.database().ref(countryCode);
const datasnapshot = await firebaseHeadingref.once('value');
this.setState(prevState=>{
...prevState,
countryName,
countrydata: [...prevState.countrydata, datasnapshot.val()],
loading: false,
},()=>console.log("done!"))
}
You need to convert the response data from firebase to an array like this:
componentDidMount() {
const countryCode = this.props.match.params.countryCode;
var countryName = getName(countryCode);
var firebaseHeadingref = firebase.database().ref(countryCode);
firebaseHeadingref.once('value').then(datasnapshot => {
const countryData = datasnapshot.val();
const countryDataArray = [];
for (const key in countryData) {
countryDataArray.push({ key, ...countryData[key]});
}
this.setState({
countrydata: countryDataArray,
countryName: countryName,
loading: false
})
});
}
Use for-in to loop through the object or use Object.keys().
const data = datasnapshot.val();
const countrydata = [];
for (let key in data) {
countrydata.push(data[key])
}
// using Object.keys()
Object.keys(data).forEach((key) => countrydata.push({ [key]: data[key]}))
this.setState({
countrydata
})
const data = {
place1: { name: 'One'},
place2: { name: 'Two'},
place3: { name: 'Three'},
};
const countrydata = [];
for (let key in data) {
countrydata.push({ [key]: data[key] });
}
console.log(countrydata);
The following code loops through a JavaScript object and collects only the properties that are arrays:
const building = this.building
let panoramaList = []
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList.push({ [key]: panoramas })
}
}
console.log(panoramaList)
In other words, it takes this:
{
name: '',
description: ''.
livingroom: Array[0],
study: Array[1],
bedroom: Array[0]
}
and turns it into this:
[
{ livingroom: Array[0] },
{ study: Array[1] },
{ bedroom: Array[0] }
]
However, what I need to produce is this:
{
livingroom: Array[0],
study: Array[1],
bedroom: Array[0]
}
How to accomplish that?
Change this :
const building = this.building
let panoramaList = []
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList.push({ [key]: panoramas })
}
}
console.log(panoramaList)
to this :
const building = this.building
let panoramaList = {}
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList[key]=panoramas
}
}
console.log(panoramaList)
Use Object.keys and try something like this:
var input = {} //...your input array
var keys = Object.keys(input);
var result = {};
keys.forEach(function (key) {
if (Array.isArray(input[key])) {
result[key] = input[key];
}
});
try this
var output = Object.keys(building).map(function(val){ return { val : building[val] } });
For the final output
var panoramaList = {}
Object.keys(building).forEach(function(val){
if ( Array.isArray(building[val] )
{
panoramaList[val] = building[val];
}
});
Make sure to define panoramaList as an object.
This works
var arrays = {
name: '',
description: '',
livingroom: ['1','www'],
study: ['2','sss'],
bedroom: ['3','aaa'],
Kitchen: ['4','bbb'],
}
const building = arrays
let panoramaList = {};
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList[key] = panoramas;
}
}
console.log(panoramaList);
https://jsbin.com/paqebupiva/1/edit?js,console,output
Rather than building a new object, you might just need to delete the unwanted properties from the object that you have:
var data = {
name: '',
description: '',
livingroom: [],
study: [1],
bedroom: [0]
};
Object.keys(data).forEach(function(key) {
if (!Array.isArray(data[key])) delete data[key];
})
document.write(JSON.stringify(data));