Variable Variables Pointing to Arrays or Nested Objects

Variable Variables Pointing to Arrays or Nested Objects

Array element approach:

  • Extract array name from the string and store it in $arrayName.
  • Extract array index from the string and store it in $arrayIndex.
  • Parse them correctly instead of as a whole.

The code:

$arrayTest  = array('value0', 'value1');
$variableArrayElement = 'arrayTest[1]';
$arrayName = substr($variableArrayElement,0,strpos($variableArrayElement,'['));
$arrayIndex = preg_replace('/[^\d\s]/', '',$variableArrayElement);

// This returns the correct 'value1'
echo ${$arrayName}[$arrayIndex];

Object properties approach:

  • Explode the string containing the class and property you want to access by its delimiter (->).
  • Assign those two variables to $class and $property.
  • Parse them separately instead of as a whole on var_dump()

The code:

$variableObjectProperty = "classObj->obj";
list($class,$property) = explode("->",$variableObjectProperty);

// This now return the values of $classObj->obj
var_dump(${$class}->{$property});

It works!

Accessing specific values in a nested object

Let's say your data structure containing your nested objects is assigned to a "data" variable:

const data = {
"Place One": {}, // etc.
}

Then in your React component template, you can loop over the "nested objects" with:

Object.keys(data).map((key) => {
const nestedObject = data[key]
return (<Marker
key={key}
position={nestedObject.coordinates} // or [nestedObject.coordinates.lat, nestedObject.coordinates.lon]
/>)
})

Accessing nested JavaScript objects and arrays by string path

I just made this based on some similar code I already had, it appears to work:

Object.byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}

Usage::

Object.byString(someObj, 'part3[0].name');

See a working demo at http://jsfiddle.net/alnitak/hEsys/

EDIT some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a try / catch block when calling, rather than having this function silently return undefined for an invalid index.

Map through nested object with variable number of fields?

you could use optional chaining so that you only map through objects that contain arrays and ignore the ones that don't


import data from "./data.json";

export default function App() {
return (
<div className="App">
{data.pagesections.map((r) => (
<>
<div>{r.title}</div>
{r.sections?.map((i) => {
return (
<>
{i.team?.map((s) => {
return <div>{s.name}</div>;
})}
</>
);
})}
</>
))}
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}

attached is a code sandbox: https://codesandbox.io/s/dreamy-mclean-wp3cb?file=/src/App.js:0-536

Concentate values in a Nested Array of Object with children in JavaScript

This would be best done with a recursive Function, that iterates through your entire data structure and sets the Path by building it up while traversing your data structure.

The first version creates the path information from scratch, by using the index of each child in the array and building up the index that gets appended to the path string.

Further below i've provided changes to this version, that uses the already existing path information and concatenates the path string as you asked for.

// Recursive Function to iterate through a possible endless nested data structure
// We provide the parameter for the previous index and parentPath to build up the path string
function recursivePath(data, index = "", parentPath = "") {

// We will get an Array with all Items as 'data' which we will loop with forEach
data.forEach((item, i) => {

// We recreate the the index of the item by adding current index of
// this item in the data array to the index structure of the parent items
let itemIndex = index !== "" ? `${index}.${i+1}` : `${i+1}`;

// We do the same for the path, we take the path of the parent
// and add the path information of this item to it.
let itemPath = `${parentPath}path${itemIndex}`;

// We set the path property of this item, which will be returned
// after all items of this data are done.
item.path = itemPath;

// We check if this item has some nested childrens and if it does,
// we will repeat this process for all those childrens
if (item.children && typeof item.children.length) {

// We provide the newly created index on which those childs will build upon
// as the same with the path.

// This can be a bit confusing, but we assume here, that the function will return
//the finished childrens and we save the result to our childrens property.
item.children = recursivePath(item.children, itemIndex, itemPath + "/");
}
});

// Lastly we iterated through all Items and are sure to set the Path for all Items
// and their childrens nested inside and return the entire data array.
return data;
}

// Your Data
const data = [{
Name: "item1",
path: "path1",
children: [{
Name: "item1.1",
path: "path1.1"
},
{
Name: "item1.2",
path: "path1.2",
children: [{
Name: "item1.2.1",
path: "path1.2.1",
children: [{
Name: "item1.2.1.1",
path: "path1.2.1.1"
}]
}, ]
}
]
}];

// We use the recursive function and output the results to the console
console.log(recursivePath(data));

Nested JSON objects - do I have to use arrays for everything?

You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

{ 
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}

You can use it like this:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix.
//I'm not sure whether you intended to do that.

Accessing Variable-Values from Complex Lists of Nested Map Objects in Flutter

Aha! Managed to figure it out. It's actually because of the brackets, and bracket-types.

Effectively, the [ bracket denotes a List, whereas the { bracket denotes a Map. I didn't understand this going in, so the notations I was using were confusing.

Now that I understand that, The notation works.

So in the above example, the method I would use to get access the to object1: data result, would be as follows.

 print(info[0][info4][0][object1]);

So in essence, due to the [] brackets, it's asking for an integer case to identify a given object, whereas the {} brackets are asking for a String case to identify to object instead. Once I understand this, the rest came automatically, and I was able to resolve the parsing of the data as needed.

Thank you for your insightful comments though!



Related Topics



Leave a reply



Submit