How to Use a String as an Array Index Path to Retrieve a Value

How to use a string as an array index path to retrieve a value?

you might use an array as path (from left to right), then a recursive function:

$indexes = {0, 'Data', 'name'};

function get_value($indexes, $arrayToAccess)
{
if(count($indexes) > 1)
return get_value(array_slice($indexes, 1), $arrayToAccess[$indexes[0]]);
else
return $arrayToAccess[$indexes[0]];
}

How to get element of array with string index path

You could take a dynamic approach for an length of the path.





function getValue(object, path) {
return path
.replace(/\[/g, '.')
.replace(/\]/g, '')
.split('.')
.filter(Boolean)
.reduce((o, k) => (o || {})[k], object);
}

console.log(getValue([{ subArray: [1, 2, 3, 4, 5] }, { subArray: [32, 321, 11] }], "[0].subArray[2]"));

Get value from object using 'Array Path'

To simplify, you could remove the primitive-check and just assume that the path is correct and leads to the value that needs to be returned, no matter whether it is primitive or not.

Secondly, you can replace the loop with a reduce() call on the path.





const getValueUsingPath = (record, path) => 
path.reduce((record, item) => record[item], record);

const record = {
firstName: "Joe Doe",
personalData: {
email: "joe.doe@test.com"
}
};
const path = ["personalData","email"];

console.log(getValueUsingPath(record, path));

How to get the value of an Array Index Within a Dictionary to Populate the Tableview

TableViews work best when dealing with Arrays. If possible, I would turn the dictionary into an array of Dictionary<String:[String]>. So it would look something like this.

var productTags: [[String: [String]]] = [
[product1: [tag1, tag2, tag3, tag4]],
[product2 : [tag1, tag2, tag3, tag4, tag5]],
[product3 : [tag1, tag2, tag3]]
]

Then from there you can return the number of product dictionaries in the array

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
Int) -> Int {

return productTags.count
}

And from there you can access the productTagDictionaries by indexPath.row

 let productTags = productTags[indexPath.row].values.first
cell.productName?.text = productTags?.first

Retrieve value from object having key and index as a string: 'array[0].key'

A bit nasty but quick and working way to do it is to use eval:

const field = 'Tags[0].name';
let stateValues = form.getState().values;
let tagName = eval(`stateValues.${ field }`)

Other approach might be to split and parse the field path using regexp and then traverse the object property by property.

Get the indexPath of the relevant element in a loop


Note: Make sure your array 'sateOfNewSongArray' has boolean types
of elements

Try following solutions:

Sample Code 1: According to your current code in your question.

func tapFunction(sender: UIButton) {

// This gives me the selected indexPath
print("ID :",sender.accessibilityIdentifier!)


if let rowIndexString = sender.accessibilityIdentifier, let rowIndex = Int(rowIndexString) {
self.sateOfNewSongArray[rowIndex] = !self.sateOfNewSongArray[rowIndex]
}
sender.isSelected = !sender.isSelected


for (index, element) in self.sateOfNewSongArray.enumerated() {

if element {
if let songName:String = songList[index] {
selectedSongList.append(songName)
}
}
}

}

Sample Code 2: More easier and concise.

func tapFunction(sender: UIButton) {

// This gives me the selected indexPath
print("ID :",sender.accessibilityIdentifier!)

if let rowIndexString = sender.accessibilityIdentifier, let rowIndex = Int(rowIndexString) {
if let songName:String = songList[rowIndex] {
selectedSongList.append(songName)
}

}

}

enumerated() is a function, returns sequence of pairs enumerating with index and element of array (by iterating elements of array)

Here is basic sample code, for your understanding. Copy and execute this code:

let songList =  [“cat”, “dog”, “elephant”]
let sateOfNewSongArray = [false, true, false]
let selectedSongList = [String]()

for (index, element) in self.sateOfNewSongArray.enumerated() {

if element {
if let animalName:String = songList[index] {
selectedSongList.append(animalName)
}
}
}

print(“selectedSongList - \(selectedSongList)”)

How to get the index of a string in an array?

You probably need to loop over the slice and find the element that you are looking for.

func main() {
path := "root/alpha/belta"
key := "alpha"
index := getIndexInPath(path, key)
fmt.Println(index)
}

func getIndexInPath(path string, key string) int {
parts := strings.Split(path, "/")
if len(parts) > 0 {
for i := len(parts) - 1; i >= 0; i-- {
if parts[i] == key {
return i
}
}
}
return -1
}

Note that the loop is backwards to address the logic issue that Burak Serdar pointed out that it may fail on a path like /a/a/a/a otherwise.

How to get value at a specific index of array In JavaScript?

Just use indexer

var valueAtIndex1 = myValues[1];

Update from Chrome 92 (released on: July 2021)

You can use at method from Array.prototype as follows:

var valueAtIndex1 = myValues.at(1);

See more details at MDN documentation.

How to find the array index with a value?

You can use indexOf:

var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1

You will get -1 if it cannot find a value in the array.



Related Topics



Leave a reply



Submit