React-Native - Object.assign children change - javascript

sry if this question is still there but i searched for it and i didn´t find a solution. Also i couldn´t get any hint out of the Developer.Mozilla website where Objects.assign etc. is described well.
The question:
How can i change the children of an object? With exactly the output i described in the following.
Sample-Code
var obj= {test: [{a: 2}, {b: 3}]};
var newChildren = [{a: 3}, {b: 5}, {c: 1}];
//I read the obj key value by the following:
var objKey = Object.entries(obj)[0][0]
//Here i want to have some code to get the following result
//My momentary regarding to #webdeb
var output = Object.assign({}, {objKey: newChildren})
actual output: // {objKey: [{a: 3}, {b: 5}, {c: 1}]}
wanted output: // {test: [{a: 3}, {b: 5}, {c: 1}]}
I have no other option to get the code in some other format so the "input" is needed in the way i described. And i need to set the objKey as a variable, because i have multiple keys in my code wich i have to set for multiple children. (Doing some filter stuff)
Thanks for your help
BR
Jonathan

First of all, don't use Object as variable Name..
Ok, lets say the Object is now obj
Without modification of the obj
var newObj = Object.assign({}, obj, {test: newChildren})
Or just, (modifies the obj)
obj.test = newChildren
Is it what you are looking for?

Following solution gave me the exact result i wanted:
obj[objKey] = newChildren;
console.log(obj) // {test: [{a: 3}, {b: 5}, {c: 1}]}
I took this solution regarding to the question:
How can I add a key/value pair to a JavaScript object?
The importance for me was to have the object-key as a variable. The described solution gives me the option to add a value tomore than just one static key.

Related

Convert all key names of an object to strings

I have an object like:
obj = {"a": 1, "b": 2, c: 3}
this object is returned by a Node.js package.
I want to pass this object to a request headers but it fails because c in that object has invalid key name I guess.
Is it possible to convert all the key names of my object to strings?
You can use JSON.stringify() to convert it to a valid JSON string:
obj = JSON.stringify({"a": 1, "b": 2, c: 3});
console.log(obj)
You can create a new object and call toString() while creating the key
const obj = {
"a": 1,
"b": 2,
c: 3
};
const newObj = {};
for (let keys in obj) {
newObj[keys.toString()]: obj[keys]
}
In JavaScript, all object keys that are not symbols are converted to strings.
obj = {1: 1}
obj['1'] = 2;
// obj is {1: 2}
If you got such an 'object' from node package it means the data has not been prepared correctly - probably somebody has created JSON by hand (writing a string instead of stringify an object).
If you want to add " to all keys and change an object to a string, so, in other words, make a JSON out of it - you can use JSON.stringify(obj) //"{"a":1,"b":2,"c":3}"
If you want to make an object out of such a broken JSON:
JSON.parse(JSON.stringify(obj)) // "{a: 1, b: 2, c: 3}"

Setting variables based off an object

I have an object which could include a mix of properties e.g.
{a: 1}, {b: 4}, {c: 2}, {a: 3, b: 1}
it will be a key with a count value next to it.
I'd like to set a bunch of variables depending on which key names are in the object, for instance:
aOnly = {a: 1}, mixOfAB = {a: 3, b: 1}
I'm using this logic in a function which will eventually return a string value. What's the best way to operate on this object, I tried using a switch but it didn't work so well. I could use a large number of if/else statements but is there something more neater?
You could do something like this:
vars = {}
function setVariable(obj) {
keys = Object.keys(obj)
name = keys.length == 1 ? keys[0] + 'Only' : 'mixOf' + keys.join('').toUpperCase()
vars[name] = obj
}
setVariable({a: 1})
console.log(vars)
setVariable({b: 4})
console.log(vars)
setVariable({c: 2})
console.log(vars)
setVariable({a: 3, b: 1})
console.log(vars)

String to Integer Object hashing in JavaScript

There are multiple questions here in SO that are similar to my question, but none really answers it completely.
Basically, I want to have objects as keys in JavaScript. I know it is possible with Map, however, it doesn't fully apply to my use-case. Here is the reason:
Let's say I have two objects, var d1 = {a: 1, b: 2} and var d2 = {a: 1, b: 2}, and a Map var m = new Map(). When adding d1 to m, when I call m.get(d2) I will get undefined. I assume it is because Map works in a reference-like manner.
However, I want the following functionality:
m.set(d1, 'hit');
m.get(d2) // should return 'hit' because properties and values of d1 = d2
One approach I thought of was not to use Map, but a simple JS object. Keys would be JSON.stringify(obj) and when I want to get a value from the object, I use JSON.parse(key) and then perform object equality check (Object.getOwnPropertyNames and then checking one-by-one).
However, I feel that this approach is way more complex and time-consuming than it should be. What I am looking for is probably a hash function of some sort that would efficiently map a object with keys of type String to values of type Number (integer in my case). Also, the ordering can be different (d1 = {a: 1, b: 2} should equal d2 = {b: 2, a: 1}).
How to design an efficient hash function to work with either JS Objects/Maps to perform the above-mentioned operations?
Write a function that turns the object into a string with the keys in a consistent order.
function objToKey(obj) {
Object.keys(obj).sort().map(k => `${k}:${obj[k]}`).join(',');
}
var d1 = {a: 1, b: 2},
d2 = {b: 2, a: 1},
m = new Map();
m.set(objToKey(d1), "foo");
console.log(m.get(objToKey(d2)));

Convert Object to string in javascript without the quotes in key

How can I convert an Object to a string so that output is something like this:
e.g. let a = {b: "c"}
Let's assume the above example is our sample Object. Now we can use JSON.stringify(a) to convert it to string but that outputs,
console.log(a) -> {"b": "c"} but I want something like this: {b: "c"} in the original Object format.
You can try using a Reg-ex, where you replace only the first occurrence of "" with white space character using $1 in the String.prototype.replace call:
const a = JSON.stringify({a: "a", b: "b", c: "c"}).replace(/"(\w+)"\s*:/g, '$1:');
console.log(a);
This code is taken from this answer.
There is a regex solution that is simpler but it has a shortcoming that is inherent to regex. For some edge cases in complex and nested objects it does not work.
const data = {a: "b", "b": "c",
c: {a: "b", "c": "d"}}
console.log(stringify(data))
function stringify(obj_from_json){
if(typeof obj_from_json !== "object" || Array.isArray(obj_from_json)){
// not an object, stringify using native function
return JSON.stringify(obj_from_json);
}
// Implements recursive object serialization according to JSON spec
// but without quotes around the keys.
let props = Object
.keys(obj_from_json)
.map(key => `${key}:${stringify(obj_from_json[key])}`)
.join(",");
return `{${props}}`;
}
You can try javascript-stringify npm package.

Join Array of Objects by Property using lodash

Is there a way using lodash or another library to join an array of objects?
I'm looking for a readymade function not a for loop.
For example:
[{a: 1}, {a:3}, {a: 4}]
//Run a function by specifing the property a and setting "," as the delimeter
Get 1,3,4
Here is your lodash answer
var arr = [{a: 1}, {a:3}, {a: 4}];
var s = _.map(arr, 'a').join(',');
//s == '1,2,3,4'
You don't need lodash for this, you can just use map and join:
let collection = [{a: 1}, {a:3}, {a: 4}];
alert(collection.map(item => item.a).join(','));

Categories