I've got this JSON data object (example):
let obj = [
{
test0: [
{testA: 'ContentA' },
{testB: 'ContenB'}
]
}
];
I'd like to replace the value of key 'testB' dynamically. I.e. I need to be able to address any item in the object and replace ist.
Here's what I am doing so far:
Therefore I programmatically generate a mixed key/index path to address the target object and it looks like this (in array form):
let path = [0,'\'test0\'',1,'\'testB\''];
In order to put this in an executable form which does the actual replacement, I convert path to JavaScript code and run it with eval. Like this:
let newText = 'ContentB';
eval(`obj[${path.join('][')}]=\'${newText}\'`);
Eval executes this code literal:
obj[0]['test0'][1]['testB'] = 'ContentB'
This works, but if possible, I'd like to know if there's an alternative way which works without using "eval".
You could use a recursive function and pass it the property path as an array of properties, like this:
function setDeepValue(obj, [prop, ...path], value) {
if (!path.length) {
obj[prop] = value;
} else {
if (!(prop in obj)) obj[prop] = {};
setDeepValue(obj[prop], path, value);
}
}
// Example:
const arr = [{
test0: [
{ testA: 'ContentA' },
{ testB: 'ContenB' }
]
}];
setDeepValue(arr, [0, "test0", 1, "testB"], "ContentB");
console.log(arr);
If you are OK with using a library, you could use Lodash, which has _.set and the more flexible _.setWith to do this.
Related
Current Situation :
[{
"Severity":1,
"Name":"Yash"
}, {
"Severity":2,
"Name":"Yashaswi"
}]
Desired Situation :
[{1: "Yash"}, {2: "Yashaswi"}]
Code being used :
widTags = ["Severity","Name"];
let tempobj = {};
for(let key in widTags) {
tempobj[key]=prop;
}
dataArrayWid.push(tempobj)
This solution does what you're suggesting without changing the syntax too much from your original code:
const original = [
{"Severity":1, "Name":"Yash"},
{"Severity":2, "Name":"Yashaswi"}
];
const final = [];
for (const oldObj of original){ // (Prefer `for...of` to iterate Arrays)
const
newObj = {},
key = oldObj["Severity"],
val = oldObj["Name"];
newObj[key] = val; // Uses Severity val as prop name & Name val as prop val
final.push(newObj);
}
console.log(final);
And this is a more concise version:
const
original = [ {"Severity":1, "Name":"Yash"}, {"Severity":2, "Name":"Yashaswi"} ],
final = original.map(obj => ( { [obj.Severity]: obj.Name } ));
console.log(final);
(Here, the .map method of Arrays makes a new Array with each element modified by a function -- in this case an Arrow function).
Note:
The extra parentheses tell JavaScript that their contents are an expression containing our Object literal to be returned, not a block of code statements.
Similarly, the extra brackets in the Object literal tell JavaScript that their contents are an expression specifying a computed property name, not a static property name,
You can achieve that by using Array.map() method.
Demo :
const dataArrayWid = [{
"Severity":1,
"Name":"Yash"
}, {
"Severity":2,
"Name":"Yashaswi"
}];
const result = dataArrayWid.map((obj) => {
return {
[obj.Severity]: obj.Name
}
});
console.log(result);
Here is my example. I have an object in Javascript that is dynamically changed.
And I want in this case the value of the property "inside" and I know that the value is in the place a[something][anotherthing][inside]. Because I saved the position in an array ["a","somethig", "anotherthing"]. my question is How do I move to that position using the keys that are in the array?. Already tried to concat the elements and the final result is something like this myObject[a][somthing][anotherthing] but the problem is that it returns 'undefined' because it's a string. Is there any chance to convert it to object or some way to get that position in the object?
var myarray = ['a', 'something', 'anotherthing'];
myObject = {
a: {
something: {
anotherthing: {
inside: 10
}
}
},
b: {
insideb: {}
}
}
Use reduce to reduce the array to a single value. You will pass in myObject as the starting point (second parameter), then use this basic callback (first parameter):
(obj, itm) => obj[itm]
When you put it all together, it will look like this:
var myarray = ['a', 'something', 'anotherthing'];
myObject = {
a: {
something: {
anotherthing: {
inside: 10
}
}
},
b: {
insideb: {
}
}
}
let result = myarray.reduce((obj, itm) => obj[itm], myObject)
console.log(result)
console.log(result.inside)
If you know the exact location of the value: myObject['a']['somthing']['anotherthing'] will give you the value.
If you need to step through the object dynamically, you can use: Object.keys(myObject).forEach(key => myObject[key]); to get the top level keys.
I have this function which takes a json parameter which contains an array of search objects.
function receiveSearch(search, json) {
return {
type: RECEIVE_SCHOOL_SEARCH,
items: json.packages,
receivedAt: Date.now(),
search: Object.assign({}, search, { next: json.next, start: search.next }),
};
}
My json
property looks like:
>0:Object
>1:Object
>2:Object
>3:Object
...{ more }
I would like to return to the search object two properties from json i.e name and suburb. How do I do this? I would prefer to use something neat like lodash/ramda/underscore but plain js is fine.
And each object contains the following properties:
id:"10360"
centreId:776
name:"ABBOTSFORD"
suburb:"TARNEIT"
The easiest solution to you problem using JavaScript could be make a new object which contains only required property and return that.
Just assume your json looks like this:
var x = {search:{id:"10360",centreId:776,name:"ABBOTSFORD",suburb:"TARNEIT"},otherProp:val}
To get required properties, you can make another function and return the object with required fields:
function ReturnRequiredPropertyObject(anyObj)
{
var newObj = {};
newObj.search = {};
newObj.search.name = anyObj.search.name;
newObj.search.suburb = anyObj.search.suburb;
return newObj;
}
You can put the above code in loop if you are getting an array of search object.
To make the above code generic, we can do the following:
function ReturnRequiredPropertyObject(anyObj,requiredPropertyArray)
{
var newObj = {};
for(var counter = 0;counter<requiredPropertyArray.length;counter++)
{
newObj[requiredPropertyArray[counter]] = anyObj[requiredPropertyArray[counter]];
}
return newObj;
}
Hope this will help.
Ok resolved.
Answer is
_.map(json,_.partialRight(_.pick,['name','suburb']));
I'm trying to restructure an object for convience.
This is the general structure:
var dictionary = { "word": {"content": "wordy"}, "palabra": {"content":"palabrota" }};
I want it to look like this:
[{"wordy":"word"},{"palabrota":"palabra"}]
And I'm trying this code out:
_.map(dictionary, function(v,k){ var new_key = v.content;return { new_key: k };} );
But instead of what I am expecting, this is the result:
[ { new_key: 'word' }, { new_key: 'palabra' } ]
How to get a key to be used as a variable in this function?
You can use the _.invertBy method (as of LoDash v4.1.0), which will give you the key and an array of the values, thus ensuring the values aren't overwritten.
var dictionary = {
"word": {"content": "wordy"},
"anotherWord": {"content": "wordy"},
"palabra": {"content":"palabrota" }
};
var result = _.invertBy(dictionary, function(item) {
return item.content;
});
// "{"wordy":["word","anotherWord"],"palabrota":["palabra"]}"
EDIT: earlier response below. This works, however the limitation is duplicate content values would overwrite the keys. The docs for _.transform below shows how to generate an array to handle duplicates, and a similar setup can be used for the regular JS approach.
You can use the _.transform method:
var transformedResult = _.transform(dictionary, function(result, value, key) {
return result[value.content] = key;
});
Or without LoDash at all, you can construct the object as intended.
var result = {};
Object.keys(dictionary).forEach(function(key) {
var value = dictionary[key].content;
result[value] = key;
});
I might recommend _.mapValues(dictionary, "content") for simplicity.
However, instead of [{"wordy":"word"},{"palabrota":"palabra"}], instead you'll get {"wordy": "word", "palabrota": "palabra"} as the result from _.mapValues. But given that you're using lodash, and lodash treats arrays and objects pretty much interchangeably, I think the non-array version would be more convenient.
I know this questions exists like 100 times, but I just can't transfer the solutions to my code, so I hope you can help me. This should be pretty easy but I just don't get it working.
This is just my code with other variable because of reasons:
My Code:
for (var key in array) {
}
The JSON I want:
[{
key: "One",
y: 5
}, {
key: "Two",
y: 2
},];
Pseudo JSON:
[{
key: key,
y: array[key].data
},{
key: key,
y: array[key].data;
},];
You can try this solution:
var data = [];
for (var key in array) {
data.push({
key : key,
y : array[key].data
});
}
console.log(data);
But, what about Pseudo JSON:?
DEMO - See console (chrome) for output
I don't understand what is 'array'. Is it an object or an array?
I think what you want might be this, if 'array' is an array:
var new_arr = [];
your_array.forEach( function(entry) {
new_arr.push({key: entry, y: entry.data}); // you should change it according to your need.
})
return JSON.stringify(new_arr);
Or if 'array' is just an object, you may need this:
var new_arr = [];
for (key in array) {
new_arr.push({key: key, y: array[key].data}); // you should change it according to your need.
}
return JSON.stringify(new_arr);
JSON is just a syntax for expressing objects and arrays independently of a scripting language's syntax.
Apparently you want to convert your array into another structure and have this expressed in JSON. The conversion to JSON is usually performed by the built-in function JSON.stringify.
Assuming your array isn't really an array (which has only numeric indices, usually without gaps), but more an object-like structure, I'd suggest the following code:
var data = []
for (var key in array)
{
data.push({key: key, y: array[key].data});
}
var json = JSON.stringify(data);
//...
If array really was an array you shouldn't use a for-in-loop. Otherwise you should consider renaming it to avoid confusion.
you can use following line to create an array of json
var jsonArr = [];
then you can create json object from following line
var obj = new Object();
put data in json object as following
obj['id'] = 123;
obj['name'] = 'ABC';
then put json object in json array as
jsonArr.push(obj);
you want to add multiple objects in json array then simply create json object and add one by one using push method.
[{"id":"123","name":"ABC"}]