I am having an object which consists of different key value pairs as below:
{1: '20', 2: '2340', 3: '1420', ...., so on} (Not related to any math equation)
I want to convert the object keys which are dynamic and have the output something like below:
[{"rate_id": '20'}, {"rate_id": '2340'}, {"rate_id": '1420'}, ...., so on}]
Any answers or suggestions are appreciated!
You should really look at how you make the first object. Looks like it is a array converted to an object. Would be easier to stat with a normal array.
If you can't do anything to change the initial value you can get the values from the object, which will return an array of the values. Then map it to the type you want.
const currentObject = { 1: "20", 2: "2340", 3: "1420" };
// Get values to a array and map them to {rate_id: value}
const rates = Object.values(currentObject).map((value) => ({
rate_id: value,
}));
// rates will look like this [{ rate_id: "20" }, { rate_id: "2340" }, { rate_id: "1420" }];
Related
I have a simple scenario where I am trying to update an array value that is part of an object, but the object does not seem to reflect the update.
Code:
var request =
{
description: 'my-desc',
details: []
};
request.details['shelf-info'] =
[
{
key: 'ShelfNumber',
value: '100'
}
];
console.log(JSON.stringify(request))
With the assignment of shelf-info, I would have expected the resulting output to be similar to:
Desired Output:
{ "description": "my-desc", "details": { "shelf-info": [ "key": "ShelfNumber", "value": "100" ] } }
but the update doesn't seem to have taken effect:
Actual Output:
{"description":"my-desc","details":[]}
I have found that I can add simple objects (strings) to an array using append, but shelf-info may or may not already be in the request.details section by the time this code gets executed...how would I handle both cases?
You want a plain object ({}) for details, not an array ([]).
When arrays are serialized to JSON, the JSON output only includes values that are stored in whole-number indices. Arrays may validly have other properties whose key names are not non-negative integers (such as the string shelf-info) but those properties are not included the JSON serialization of the array.
You're using an array as if it's an object, which it technically is, but that won't add anything to the array, and it won't convert the array to a regular object with key/value pairs.
Easy fix:
var request = {
description: 'my-desc',
details: { }
};
Also since it's 2020 you should be using let instead of var in most cases.
Try Below. Detail property should be an object.
var request =
{
description: 'my-desc',
details: {}
};
request.details['shelf-info'] =
[
{
key: 'ShelfNumber',
value: '100'
}
];
console.log(JSON.stringify(request))
I have an array of objects. In that array of objects I have to find which keys have empty value with index of array. Array list is given below:
let fruits=[
{name:"apple",quantity:2,price:"" },
{name:"orange",quantity:" ",price:"2"},
{name:"banana",quantity:" ",price:""}
];
so here i have to find any of object key having empty value which should return key with index. i have tried using .findIndex() and other methods but unfortunately i can't. I am new to es6 and typescript. i need to check key with empty value in array of object.
This should do what you want. It will "map" through your array and will find for each object the keys of properties that are empty or a blank string. Then the so filtered items are "mapped" again with all the found keys being "joined" into a comma separated list (property "f") together with the "id" of the object. As a last step I filter out all those objects where the "f" property actually contains key name(s).
let fruits=[
{name:"apple",quantity:2,price:"" },
{name:"orange",quantity:" ",price:"2"},
{name:"pineapple",quantity:3,price:5},
{name:"banana",quantity:" ",price:""}
];
let empty=fruits.map(f=>
Object.keys(f).filter(k=>!(""+f[k]).trim()))
.map((f,i)=>({id:i,f:f.join(',')}))
.filter(f=>f.f)
console.log(empty)
In my example I added another fruit ("pineapple") with a complete set of filled properties. My snippet considers strings containing only blanks as "empty".
Please try the following example
let fruits = [
{ name: "apple", quantity: 2, price: "" },
{ name: "orange", quantity: "", price: "2" },
{ name: "banana", quantity: "", price: "" },
];
const output = fruits.reduce((previousValue, currentValue, currentIndex) => {
const keys = Object.keys(currentValue).filter((key) => !currentValue[key]);
if (keys.length) {
previousValue[currentIndex] = keys;
}
return previousValue;
}, {});
console.log(output);
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Assuming you're looking to get fruits that do not have a price value, you'll need to run a filter since your fruits is an array.
let emptyPriceFruits = fruits.filter((fruit) => !fruit.price)
Additional reading on .filter - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
How about this one, by taking entries of object and then using filter to identify deuplicate values:
var fruits=[ {name:"apple",quantity:2,price:"", pal:null }, {name:"orange",quantity:" ",price:"2"}, {name:"banana",quantity:" ",price:""}];
var emptyResult = fruits.map(k=>Object.fromEntries(Object.entries(k).filter(([k,v])=>typeof v=='string' && !v.trim())));
console.log(emptyResult);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
{"1":"val1","2":"val2","3":"val3"}
i want it to converted like this:
{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
little Help Please would be much appricated
You can't use the same key name in one object.
instead you can do this.
const origin = {"1":"val1","2":"val2","3":"val3"}
const converted = Object.entries(origin).map( ([key,value]) => ({id: key, value }) );
console.log(converted);
What you have posted is invalid.
What you might want is:
const object = {"1":"val1","2":"val2","3":"val3"};
console.log(Object.entries(object));
// or
console.log(Object.keys(object).map(i => ({Id: i, value: object[i]})));
You could use a loop over Object.entries.
E.g. something like:
const newObjArr = [];
for(let [key, value] of Object.entries(obj)){
newObj.push({Id: key, value});
}
The above would return an array of objects, but I'm sure you can amend it to your particular use case.
const data = {"1":"val1","2":"val2","3":"val3"};
const result = Object.keys(data).map((key) => ({ id: key, value: data[key] }));
The result will be [{ id: "1", value: "val1" }, { id: "2", value: "val2" }, { id: "3", value: "val3" }]
As pointed out this is invalis. If you want to convert it if would look like this:
[{"Id":"1","value":"val1"},{"Id":"2","value":"val2"},{"Id":"3","value":"val3"}]
You can make an function that converts this.
const object = {"1":"val1","2":"val2","3":"val3"};
console.log(Convert(object));
function Convert(obj){
return Object.keys(obj).map(i => ({Id: i, value: obj[i]}));
}
You cannot do this. Object is a unique key value pair.
{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
Suppose you want to merge two object and What if both the object has same key, it simply merge the last objects value and have only one key value.
You can convert your large object to several small objects and store them in an array as this snippet shows. (It could be much shorter, but this verbose demo should be easier to understand.)
// Defines a single object with several properties
const originalObject = { "1" : "val1", "2" : "val2", "3" : "val3" }
// Defines an empty array where we can add small objects
const destinationArray = [];
// Object.entries gives us an array of "entries", which are length-2 arrays
const entries = Object.entries(originalObject);
// `for...of` loops through an array
for(let currentEntry of entries){
// Each "entry" is an array with two elements
const theKey = currentEntry[0]; // First element is the key
const theValue = currentEntry[1]; // Second element is the value
// Uses the two elements as values in a new object
const smallObject = { id: theKey, value: theValue };
// Adds the new object to our array
destinationArray.push(smallObject);
} // End of for loop (reiterates if there are more entries)
// Prints completed array of small objects to the browser console
console.log(destinationArray);
const obj = {"1":"val1","2":"val2","3":"val3"}
const newObject = Object.keys(obj).map(e => {
return {ID: e , value : obj[e] }
});
console.log(newObject); // [ { ID: '1', value: 'val1' },
{ ID: '2', value: 'val2' },
{ ID: '3', value: 'val3' } ]
it will give u an array of object, later u need to convert it to object and flat the object:
How do I convert array of Objects into one Object in JavaScript?
how to convert this nested object into a flat object?
Basically I have got an object, which will be multi-dimensional and the properties could be named anything and it could have many dimensions.
At some point I will need to append/splice a property within this object, from code which won't know it's position.
So, an example object:
let obj = {
response: {
locations: {
data: [
0: Object,
1: Object,
2: Object,
]
}
},
endpoint: null
}
I need to splice out data.locations.data[1], the only information I have is the below array and the index. Obviously I will know the first property will be response.
['locations','data']
index: 1
Edit:
My mistake, the data property has an array value not an object!
You can use Array#reduce() and pass in obj.response as the start value to get at the nested parent which based on the array shown would be obj.response.locations.data.
Then splice() the indexed item in that parent or do whatever other modifications are needed
const arr = ['locations','data'],
index= 1,
obj = {
response: {
locations: {
data: [{id:1},{id:2}, {id:3}]
}
},
endpoint: null
}
const targetArr = arr.reduce((a,c)=> (a[c]), obj.response);
targetArr.splice(index,1);
console.log(obj)
I have associative array.
It's a key(number) and value(object).
I need to keep state of this array same as it is I just need to update one object property.
Example of array:
5678: {OrderId: 1, Title: "Example 1", Users: [{UserId: 1}, {UserId: 2}, {UserId: 3}]}
5679: {OrderId: 2, Title: "Example 2", Users: [{UserId: 1}, {UserId: 2}, {UserId: 3}]}
I need to update Users array property.
I tried this but it doesn't work:
ordersAssociativeArray: {
...state.ordersAssociativeArray,
[action.key]: {
...state.ordersAssociativeArray[action.key],
Users: action.updatedUsers
}
}
This is data inside reducer.
What I did wrong how to fix this?
Something that might help.
When I inspect values in chrome I check previous value and value after execution of my code above:
Before:
ordersAssociativeArray:Array(22) > 5678: Order {OrderId: ...}
After:
ordersAssociativeArray: > 5678: {OrderId: ...}
Solution (code in my reducer)
let temp = Object.assign([], state.ordersAssociativeArray);
temp[action.key].Users = action.updatedUsers;
return {
...state,
ordersAssociativeArray: temp
}
So this code is working fine.
But I still don't understand why? So I have solution but would like if someone can explain me why this way is working and first not?
If it could help here how I put objects in this associative array initialy:
ordersAssociativeArray[someID] = someObject // this object is created by 'new Order(par1, par2 etc.)'
What you are doing is correct, as demonstrated by this fiddle. There may be problem somewhere else in your code.
Something that I would recommend for you is to separate your reducer into two functions, ordersReducer and orderReducer. This way you will avoid the excessive use of dots, which may be what caused you to doubt the correctness of your code.
For example, something like:
const ordersReducer = (state, action) => {
const order = state[action.key]
return {
...state,
[action.key]: orderReducer(order, action)
}
}
const orderReducer = (state, action) => {
return {
...state,
Users: action.updatedUsers
}
}
I hope you find your bug!
Update
In your solution you use let temp = Object.assign([], state.ordersAssociativeArray);. This is fine, but I thought you should know that it is sometimes preferable to use a {} even when you are indexing by numbers.
Arrays in javascript aren't great for representing normalized data, because if an id is missing the js array will still have an undefined entry at that index. For example,
const orders = []
array[5000] = 1 // now my array has 4999 undefined entries
If you use an object with integer keys, on the other hand, you get nice tightly packed entries.
const orders = {}
orders[5000] = 1 // { 5000: 1 } no undefined entries
Here is an article about normalizing state shape in redux. Notice how they migrate from using an array in the original example, to an object with keys like users1.
The problem can be that you're using array in the state but in the reducer you're putting as object. Try doing:
ordersAssociativeArray: [ //an array and not an object
...state.ordersAssociativeArray,
[action.key]: {
...state.ordersAssociativeArray[action.key],
Users: action.updatedUsers
}
]
It will put ordersAssociative array in your state and not an object.